检查是否所有对象键都作为对象数组中的值存在

假设我有这两个实体


const obj1 = {key1: "", key2: "", key3: ""};

const array2 = [

  {

    name: "key1",

  }]

如何检查是否array2有一个对象具有每个字段的名称obj1?


基本上我想以数组 2 变成这样结束:


const array2 = [

  {

    name: "key1",

  },

{

    name: "key2",

  },

{

    name: "key3",

  }]


慕娘9325324
浏览 91回答 1
1回答

慕田峪9158850

是这样的吗?const obj1 = {&nbsp; &nbsp; key1: "",&nbsp; &nbsp; key2: "",&nbsp; &nbsp; key3: ""};const array2 = [{&nbsp; &nbsp; name: "key1",}, {&nbsp; &nbsp; name: "key2",}];const obj1Keys = Object.keys(obj1);const array2KeyNames = array2.reduce((array2KeyNames, obj) => {&nbsp; &nbsp; array2KeyNames.push(obj.name);&nbsp; &nbsp; return array2KeyNames;}, []);for (let i = 0; i < obj1Keys.length; i++) {&nbsp; &nbsp; if (!array2KeyNames.includes(obj1Keys[i])) {&nbsp; &nbsp; &nbsp; &nbsp; console.log(obj1Keys[i], ' is not in the array2');&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript