我根据查询从firebase中检索了以下数据。 我试图创建一个2D数组但没有成功。
我该怎么做?
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"}
预期结果:
[
["6220 Lawson Dr, Haymarket, VA 20169", "Dave", "A"],
["2121 I St NW, Washington, DC 20052", "George W", "A"]
]
我的代码:
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);
答案 0 :(得分:2)
您可以将两个对象移动到一个数组中,使用Object.keys
和Array#map
遍历每个对象并仅返回值。
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);
&#13;
答案 1 :(得分:0)
您可以使用.map()
来执行以下操作:
const myArr = data.map(i => [i.address, i.name, i.petProfile])
这将从data
中的每个元素中提取地址,名称和petProfile,并将其放入myArray
。