首页 > 解决方案 > 通过javascript中的特定值将数组与对象键/值进行比较

问题描述

我需要创建一个新的对象键/值。在其中我需要来自已经存在的键/值对象的值,并且我需要添加仅在数组中的值。

数组:

[{ name: "Computer", name: "Car", name: "House", name: "Flower"}]

对象键/值:

{ computer: { title: 'Computer', color: 'Black' }, house: { title: 'House', color: 'Red' }}

所以在这种情况下,新对象需要是:

{ computer: { title: 'Computer', color: 'Black' }, car: { title: 'Car', color:'' }, house: { title: 'House', color: 'Red' }, flower: { title: 'Flower', color:'' } } 

实现这一目标的最简单方法是什么?我正在考虑遍历数组比较它们之间的值并提取重复的值,但我不知道该怎么做。

标签: javascriptarraystypescriptcomparisonkey-value

解决方案


我假设第一个数组是一个由单个对象组成的数组,每个对象在数组中都有一个'name'as的键arr

const arr = [ {name: "Computer"}, {name: "Car"}, {name: "House"}, {name: "Flower"}];
const objVal = { 
        computer: { title: 'Computer', color: 'Black' }, 
        house: { title: 'House', color: 'Red' }
        };
const expected = { 
        computer: { title: 'Computer', color: 'Black' }, 
        car: { title: 'Car', color:'' }, 
        house: { title: 'House', color: 'Red' }, 
        flower: { title: 'Flower', color:'' } 
        } 

let returnObj = {};

arr.forEach((element) => {
    const name = element.name;
    if (objVal[name.toLowerCase()]) {
        returnObj[name.toLowerCase()] = objVal[name.toLowerCase()];
    } else {
      returnObj[name.toLowerCase()] = {
        title: name,
        color: ''
      }
    }
});

console.log(returnObj);

推荐阅读