gpt4 book ai didi

javascript - 如何将对象的对象数组转换为一维数组?

转载 作者:行者123 更新时间:2023-12-03 01:51:04 25 4
gpt4 key购买 nike

我有一个对象内有对象的javascript数组的示例。所以我基本上只想将其放入一维数组中。

我在 SO 上搜索了很多问题,但没有一个符合我的要求。

我有什么

[
{
"id": "59cf758f7bdf8d2e0c1c68c7",
"value": {
"city": "Mahbubnagar",
"state": "Andhra Pradesh",
"country": "India"
}
},
{
"id": "59cf758f7bdf8d2e0c1c68c8",
"value": {
"city": "Udgir",
"state": "Maharashtra",
"country": "India"
}
},
{
"id": "59cf758f7bdf8d2e0c1c68c9",
"value": {
"city": "Umarga",
"state": "Maharashtra",
"country": "India"
}
},
{
"id": "59cf758f7bdf8d2e0c1c68ca",
"value": {
"city": "Umarkhed",
"state": "Maharashtra",
"country": "India"
}
},
{
"id": "59cf758f7bdf8d2e0c1c68cb",
"value": {
"city": "Umred",
"state": "Maharashtra",
"country": "India"
}
}
]

我只是想把这个对象数组放入一个数组中

[
"59cf758f7bdf8d2e0c1c68c7",
"Mahbubnagar",
"Andhra Pradesh",
"India",
],[
"59cf758f7bdf8d2e0c1c68c9",
"Umarga",
"Maharashtra",
"India",
],[
"59cf758f7bdf8d2e0c1c68ca",
"Umarkhed",
"Maharashtra",
"India",
],[
"59cf758f7bdf8d2e0c1c68c7",
"Mahbubnagar",
"Andhra Pradesh",
"India",
],

对象数组可以有更多的子对象,换句话说,你可以说它的动态内容。

到目前为止我用过的是

var object= property.value.elements;
var finalArray = object.map(function (obj) {
return obj.id;
});
console.log(finalArray);

这只给我 ID 列表

这不是重复的问题,请在将其标记为重复之前进行验证。

最佳答案

您可以检查对象的值是否是一个对象,并采用扁平值作为结果。

function flat(object) {
return Object
.values(object)
.reduce((r, v) => r.concat(v && typeof v === 'object' ? flat(v) : v), []);
}

var array = [{ id: "59cf758f7bdf8d2e0c1c68c7", value: { city: "Mahbubnagar", state: "Andhra Pradesh", country: "India" } }, { id: "59cf758f7bdf8d2e0c1c68c8", value: { city: "Udgir", state: "Maharashtra", country: "India" } }, { id: "59cf758f7bdf8d2e0c1c68c9", value: { city: "Umarga", state: "Maharashtra", country: "India" } }, { id: "59cf758f7bdf8d2e0c1c68ca", value: { city: "Umarkhed", state: "Maharashtra", country: "India" } }, { id: "59cf758f7bdf8d2e0c1c68cb", value: { city: "Umred", state: "Maharashtra", country: "India" } }],
result = array.map(flat);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何将对象的对象数组转换为一维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50410657/

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