假設我有以下 JSON 陣列:
[
{
"name": "x",
"category": "y",
"attributes": {
"name": "a",
"description": "b"
}
},
{
"name": "x",
"category": "y",
"attributes": {
"name": "c",
"description": "d"
}
}
]
如何組合每個屬性相同的元素,但將不同的屬性添加到嵌套陣列中:
[
{
"name": "x",
"category": "y",
"attributes": [
{
"name": "a",
"description": "b"
},
{
"name": "c",
"description": "d"
}
]
}
]
更具體地說,任何不同的元素都應該附加到陣列中——例如,如果名稱為“c”的屬性的描述為“b”,我仍然希望將整個屬性附加到“屬性”串列中。
通過廣泛的搜索,我一直無法在 StackOverflow 上找到這個問題。我感謝您的幫助!
uj5u.com熱心網友回復:
最直接的方法是使用reduce函式
const data = [
{
name: 'x',
category: 'y',
attributes: {
name: 'a',
description: 'b',
},
},
{
name: 'x',
category: 'y',
attributes: {
name: 'c',
description: 'd',
},
},
];
const answer = data.reduce((result, current) => {
const findIndex = result.findIndex((item) => item.name === current.name);
// if the name does not exist in the result, append it to the result array
if (findIndex === -1) {
return [
...result,
{
name: current.name,
category: current.category,
attributes: [current.attributes],
},
];
}
return result.map((value, index) => {
if (index === findIndex) {
value.attributes.push(current.attributes);
}
return value;
});
}, []);
console.log(answer);
uj5u.com熱心網友回復:
減少可以完成這項作業。這是一種方法
const myJson = [{
"name": "x",
"category": "y",
"attributes": {
"name": "a",
"description": "b"
}
},
{
"name": "x",
"category": "y",
"attributes": {
"name": "c",
"description": "d"
}
}
]
const result = Object.values(
myJson.reduce((acc, {
name,
category,
attributes
}) => (((acc[`${name}_${category}`] ??= {
name,
category,
attributes: []
}).attributes.push(attributes)), acc), {})
);
console.log(result)
uj5u.com熱心網友回復:
//It's very simple and best for huge data
var arr = [
{
"name": "x",
"category": "y",
"attributes": {
"name": "a",
"description": "b"
}
},
{
"name": "x",
"category": "y",
"attributes": {
"name": "c",
"description": "d"
}
}
];
var newArr = [];
var objKeyValue = {};
arr.forEach(rec => {
if (objKeyValue[rec.name rec.category])
objKeyValue[rec.name rec.category].attributes.push(rec.attributes);
else objKeyValue[rec.name rec.category] = { name: rec.name, category: rec.category, attributes: [rec.attributes] };
});
console.log("Output", Object.values(objKeyValue));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/315955.html
標籤:javascript 数组 json
