gpt4 book ai didi

JavaScript 将具有特定结构的对象转换为数组

转载 作者:行者123 更新时间:2023-11-30 08:21:56 26 4
gpt4 key购买 nike

预期输入:

const all = [
{ "Attribute_Values" : [ "36", "38", "40" ],
"Attribute" : "size"
},
{ "Attribute_Values" : [ "blue", "black" ],
"Attribute" : "color"
}
];

预期输出:

[ {size: '36', color: 'blue'},
{size: '36', color: 'black'},
{size: '38', color: 'blue'},
{size: '38', color: 'black'},
{size: '40', color: 'blue'},
{size: '40', color: 'black'} ]

最佳答案

首先生成一个包含所需键和值的对象,然后采用递归函数分离所有键/值对,并通过迭代值构建新的笛卡尔积,如果包含对象的数组调用 getCartesian再次构建新对象。

这也适用于嵌套对象。

function getCartesian(object) {
return Object.entries(object).reduce((r, [k, v]) => {
var temp = [];
r.forEach(s =>
(Array.isArray(v) ? v : [v]).forEach(w =>
(w && typeof w === 'object' ? getCartesian(w) : [w]).forEach(x =>
temp.push(Object.assign({}, s, { [k]: x }))
)
)
);
return temp;
}, [{}]);
}

var all = [{ Attribute_Values: ["36", "38", "40"], Attribute: "size" }, { Attribute_Values: ["blue", "black"], Attribute: "color" }],
temp = Object.assign(...all.map(({ Attribute_Values, Attribute }) => ({ [Attribute]: Attribute_Values }))),
cartesian = getCartesian(temp);

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

关于JavaScript 将具有特定结构的对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52101960/

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