我在展平数组方面遇到问题。
鉴于结构如下
{
"name": "Somename",
"property": [
[
{
"prop": "someprop",
"other": "someother"
},
{
"prop": "someprop",
"other": "someother"
}
],
[
{
"prop": "someprop",
"other": "someother"
},
{
"prop": "someprop",
"other": "someother"
},
{
"prop": "someprop",
"other": "someother"
},
{
"prop": "someprop",
"other": "someother"
}
],
[
{
"prop": "someprop",
"other": "someother"
}
]
]
}
如何将匹配扁平化为单个对象数组或实际上具有扁平结构,其中所有嵌套项都位于单个数组或对象中?
到目前为止,我已经通过整理数据取得了进展,但似乎陷入了困境,我几乎可以使用任何库或工具以及最新的 JS 功能。
我尝试过映射值,使用lodash deepMerge减少它,但似乎无法实现我想要的。
输入:
const data = [
{
"sport": "Handball",
"matches": [
[
{
"home": "Izmir BSB SK (Youth) (Wom)",
"away": "Bursa Osmangazi (Youth) (Wom)",
"ID": "3092996854"
}
],
[
{
"home": "Al Muheet U21",
"away": "Al Mohmel U21",
"ID": "3092999932"
}
]
]
},
{
"sport": "Volleyball",
"matches": [
[
{
"home": "Ji-Hee Choi/Michika Ozeki",
"away": "Panji Ahmad Maulana",
"ID": "3093062401"
},
{
"home": "Ryazan (Wom)",
"away": "Angara Irkutsk (Wom)",
"ID": "3093062393"
}
],
[
{
"home": "CF Carthage (Wom)",
"away": "Winner - Broughton Excels",
"ID": "3093721823"
}
],
[
{
"home": "Ankara Yildirim Beyazit Universitesi (Wom)",
"away": "Saglik Bilimleri Universitesi (Wom)",
"ID": "3093058567"
}
]
]
}
]
每个 matches 属性的预期输出:
{
"sport": "Handball",
"matches": [
{home: '...', other: '...', id: '...'},
{home: '...', other: '...', id: '...'},
{home: '...', other: '...', id: '...'},
{home: '...', other: '...', id: '...'},
]
}
最佳答案
您可以使用函数reduce
并使用函数Array.isArray
检查数组对象。
var data = { "name": "Somename", "property": [ [ { "prop": "someprop", "other": "someother" }, { "prop": "someprop", "other": "someother" } ], [ { "prop": "someprop", "other": "someother" }, { "prop": "someprop", "other": "someother" }, { "prop": "someprop", "other": "someother" }, { "prop": "someprop", "other": "someother" } ], [ { "prop": "someprop", "other": "someother" } ] ]};
data.property = data.property.reduce((mapped, p) =>
[...mapped, ...(Array.isArray(p) ? p : [p])], []);
// ^
// |
// +- This is to check for situations where
// a particular object is not an array.
console.log(JSON.stringify(data, null, 2));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 展平包含对象的数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49175813/