检查字符串数组中是否存在对象值数组,如果不存在则创建一个对象

check if an array of object value exist in array of strings, and create a object if not exist

假设我有两个如下所示的数组=>

const arr1 = {
 books: ["a1","a2"],
 categories: ["c1", "c2"]
}

const arr2 = [
{
"books": [{
 label: "a1",
  count: 2
},
{
 label: "a3",
  count: 4
}],

"categories": [{
 label: "c2",
  count: 2
},
{
 label: "c3",
  count: 4
}]
}]

如何检查 arr1 中的所有书籍是否都存在于 arr2[0].books 中,即字符串数组?如果它不存在,那么我想在 arr2[0].books{label: "whatever string doesn't exist in arr2", count: 0} 中创建一个对象。 我想为每个 arr2 对象 bookscategories

我尝试了以下代码:-

arr1.books.map(i => {
   return arr2[0].books.find(item => i == item.label);
});

预期结果 -

arr2 = [
{
"books": [{
 label: "a1",
  count: 2
},
{
 label: "a3",
  count: 4
}, {
 label: "a2",
  count: 0
}

],

"categories": [{
 label: "c2",
  count: 2
},
{
 label: "c3",
  count: 4
},{
 label: "c1",
  count: 0
}]
}]

label: a2 被添加到 arr2 中的 books,因为它不存在,类似地 c1 被添加到 categoriesarr2 中.并根据计数 desc

排序

你可以做到这一点

const arr1 = {
 books: ["a1","a2"],
 categories: ["c1", "c2"]
}

const arr2 = [
{
"books": [{
 label: "a1",
  count: 2
},
{
 label: "a3",
  count: 4
}],

"categories": [{
 label: "c2",
  count: 2
},
{
 label: "c3",
  count: 4
}]
}]

const arr3 = Object.fromEntries(Object.entries(arr1).map(([key, value]) => [
 key,
 value.map(v => arr2[0][key].find(({label}) => label === v) || {label: v, count: 0})
] ))
console.log(arr3)

你可以这样做:

const arr1 = { books: ['a1', 'a2'], categories: ['c1', 'c2'] }
const arr2 = [
  {
    books: [{ label: 'a1', count: 2 }, { label: 'a3', count: 4 }],
    categories: [{ label: 'c2', count: 2 }, { label: 'c3', count: 4 }]
  }
]

arr2.forEach(obj => Object.keys(obj).forEach(key => arr1[key]
  .filter(name => !obj[key].some(({ label }) => label === name))
  .forEach(name => obj[key].push({ label: name, count: 0 }))
))

console.log(arr2)