2

I retrieved the data below from firebase based on a query. I've tried to create a 2D array without success.

How can I do it?

Object {address: "6220 Lawson Dr, Haymarket, VA 20169", name: "Dave", petProfile: "A"}

Object {address: "2121 I St NW, Washington, DC 20052", name: "George W", petProfile: "A"}

Expected result:

[
 ["6220 Lawson Dr, Haymarket, VA 20169", "Dave", "A"],
 ["2121 I St NW, Washington, DC 20052", "George W", "A"]
]

My code:

var myArr = [];          
for (var i=0, len=data.length; i<len; i++) {
    for (var j=0, len2=data[i].length; j<len2; j++) {
        var sub = data[i][j]; 
    }
}
 myArr.push(sub);
 console.log(myArr);
2
  • Why are you creating a 2d array? Are you sure you couldn't use an array of objects? Commented Apr 6, 2017 at 19:53
  • 1
    You're right. I think an array of objects will work too. Commented Apr 6, 2017 at 20:01

2 Answers 2

2

You could move both objects into an array, iterate over each object with Object.keys and Array#map and return just the values.

var obj1 = {address: "6220 Lawson Dr, Haymarket, VA 20169", name: "Dave", petProfile: "A"},
    obj2 = {address: "2121 I St NW, Washington, DC 20052", name: "George W", petProfile: "A"},
    arr = [obj1, obj2],
    res = arr.map(c => Object.keys(c).map(v => c[v]));
    
    console.log(res);

Sign up to request clarification or add additional context in comments.

Comments

0

You can use .map() to simply do:

const myArr = data.map(i => [i.address, i.name, i.petProfile])

This will extract the addresses, names, and petProfiles from every element in data and put in in myArray.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.