gpt4 book ai didi

javascript - 使用对象创建二维数组 - Javascript

转载 作者:行者123 更新时间:2023-11-29 21:07:42 24 4
gpt4 key购买 nike

我根据查询从 firebase 检索了以下数据。我尝试创建一个二维数组但没有成功。

我该怎么做?

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);

最佳答案

您可以将两个对象移动到一个数组中,使用 Object.keysArray#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);

关于javascript - 使用对象创建二维数组 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43264493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com