javascript - 通过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:'' } }
实现这一目标的最简单方法是什么?我正在考虑遍历数组比较它们之间的值并提取重复的值,但我不知道该怎么做。
解决方案
我假设第一个数组是一个由单个对象组成的数组,每个对象在数组中都有一个'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);
推荐阅读
- javascript - 如何使用时刻获取重复日期
- bash - grep 或 awk,如何将数据转换为 csv 文件中的多列
- r - 选择使用 Tesseract OCR 提取的部分文本
- java - 在每个片段中创建单独的选项菜单
- c - 直接 C 指针转换
- algorithm - 找到满足一组条件的数字序列的算法
- java - JavaFX UI 在事件侦听器中的 JavaFX 应用程序线程中冻结,但可与 Platform.runLater 一起使用
- neo4j - 将 Neo4j 添加到 Gremlin 服务器 - 如何?
- git - 如何重新定位整个提交图?
- reactjs - 将 Prop 传递给函数