【问题标题】:Javascript: Add object to Existing Array of objects with the same key not workingJavascript:将对象添加到具有相同键的现有对象数组不起作用
【发布时间】:2020-10-15 10:19:22
【问题描述】:

我正在尝试将 newList 添加到 Grouped 数组,其中 Grouped 数组名称与 newList 名称相同。例如,将“乳制品和鸡蛋”对象从 newList 连接到 Grouped 数组。这在所需的输出中得到了证明。

我尝试过的:

const existingCatrgory = Grouped.findIndex(
    item => item.name === 'Spices' || 'Dairy and Eggs' || 'Produce'
);

if (existingCatrgory >= 0) {
    const findShoppingCategory = Grouped.filter(x => x.name === 'Spices' || 'Dairy and Eggs' || 'Produce')
    const merge = findShoppingCategory.map((element) => {
        return {
            ...element,
            data: element.data.concat(newList)
        };
    });
} else {
    return Grouped.concat(newList)
}

这是newList

const newList = [{
        data: [{
            value: "whipped cream"
        }, ],
        name: "Dairy and Eggs",
    },
    {
        data: [{
            value: "mushrooms",
        }],
        name: "Produce",
    }
]

这是Grouped Array

const Grouped = [{
        data: [{
            value: "paprika",
        }, ],
        name: "Spices",
    },
    {
        data: [
            {value: "milk"},
            {value: "Blue cheese"},
        ],
        name: "Dairy and Eggs",
    },
];

期望的输出:

const Output = [{
    data: [
        { value: "paprika" },],
    name: "Spices",
},
{
    data: [
        { value: "milk" },
        { value: "Blue cheese" },
        { value: "whipped cream" },
    ],
    name: "Dairy and Eggs"
},
{
    data: [
        { value: "mushrooms" }
    ],
    name: "Produce",
}
];

【问题讨论】:

    标签: javascript arrays sorting object


    【解决方案1】:

    这是一种方法:

    const Grouped = [{
            data: [{
                value: "paprika",
            }, ],
            name: "Spices"
        },
        {
            data: [
                {value: "milk"},
                {value: "Blue cheese"},
            ],
            name: "Dairy and Eggs"
        },
    ];
    
    const newList = [{
            data: [{
                value: "whipped cream"
            }, ],
            name: "Dairy and Eggs"
        },
        {
            data: [{
                value: "mushrooms",
            }],
            name: "Produce"
        }
    ]
    
    const mergedList = JSON.parse(JSON.stringify(Grouped));
    
    newList.forEach(function(item){
      let thisGroup = mergedList.filter(g => g.name == item.name);
      if (thisGroup.length > 0) {
        for (let i = 0; i < item.data.length; i++) {
          thisGroup[0].data.push({"value": item.data[i].value});
        }
      } else {
        mergedList.push(item);
      }
    })
    
    console.log(mergedList);

    只需遍历每个新项目并检查名称是否已存在,如果存在,请将新 data.value 附加到现有数据列表中。如果它不存在,请为该项目创建一个新条目。

    根据要求,我更新了代码,包括获取 Grouped 数组的副本并将其合并到其中。由于 Grouped 数组结构简单,我使用 JSON 将其字符串化并解析回一个新数组。

    【讨论】:

    • 哇,谢谢你的回答。你能让它返回一个新数组而不是变异状态吗?非常感谢你!!!!
    • np - 我已经更新了我的答案,包括获取分组数组的副本并与副本而不是原始数组合并。
    【解决方案2】:

    这是另一个使用 findIndex 并创建新项目或添加到现有数据的解决方案。

    newList.forEach(newItem =>{
        let index = Grouped.findIndex(item => item.name ===newItem.name)
        if(index===-1){
            Grouped.push(newItem)
        }else{
            Grouped[index].data.push(...newItem.data)
        }
    })
    

    【讨论】:

      猜你喜欢
      • 2020-12-16
      • 2016-07-18
      • 2022-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 2020-02-22
      相关资源
      最近更新 更多