gpt4 book ai didi

Javascript/ES6 从一级对象生成嵌套数组

转载 作者:行者123 更新时间:2023-11-30 08:24:47 25 4
gpt4 key购买 nike

我确实有一个来自这样的 API 的对象:

  this.Variations = [
{
attributes: [
{name: "Cor", option: "Preto"},
{name: "Tamanho", option: "P"},
{name: "Tecido", option: "Algodao"},
],
id : 1
},
{
attributes: [
{name: "Cor", option: "Preto"},
{name: "Tamanho", option: "P"},
{name: "Tecido", option: "Elastano"},
],
id : 2
},
{
attributes: [
{name: "Cor", option: "Preto"},
{name: "Tamanho", option: "M"},
{name: "Tecido", option: "Algodao"},
],
id : 3
}, ...

我必须从中生成一个嵌套数组,以创建我需要的体验,即用户按时间选择一个属性,并加载可能的选项。

我现在为此苦苦挣扎了很长时间,但一无所获。

我相信我需要一个类似的数组:

array['Preto']['P']['Algodao'] = info;
array['Preto']['P']['Elastano'] = info;
array['Preto']['M']['Algodao'] = info;

关于如何做到这一点有什么建议吗?

最佳答案

假设 info 是指 id 值,试试这个方法

var output = variations.map( s => ({ [s.attributes[0].option ] : 
{ [s.attributes[1].option ] :
{ [ s.attributes[2].option] : s.id } } }) );

演示

var variations = [{
attributes: [{
name: "Cor",
option: "Preto"
},
{
name: "Tamanho",
option: "P"
},
{
name: "Tecido",
option: "Algodao"
},
],
id: 1
},
{
attributes: [{
name: "Cor",
option: "Preto"
},
{
name: "Tamanho",
option: "P"
},
{
name: "Tecido",
option: "Elastano"
},
],
id: 2
},
{
attributes: [{
name: "Cor",
option: "Preto"
},
{
name: "Tamanho",
option: "M"
},
{
name: "Tecido",
option: "Algodao"
},
],
id: 3
}
];

var output = variations.map( s => ({ [s.attributes[0].option ] : { [s.attributes[1].option ] : { [ s.attributes[2].option] : s.id } } }) );

console.log( output );

关于Javascript/ES6 从一级对象生成嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47475103/

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