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

Time:05-05

suppose i have two arrays like below =>

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
}]
}]

How can i check if all the books in arr1 which is array of strings exist in arr2[0].books which is array of objects? If it doesnt exist then i want to create an object in arr2[0].books with {label: "whatever string doesn't exist in arr2", count: 0}. I want to do it for each arr2 objects books and categories

I tried below code: -

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

Expected Result -

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
}]
}]

which is label: a2 is added to books in arr2 as it didnt exist, and similarly c1 in arr2 of categories . and sort based on count desc

CodePudding user response:

You can do:

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)

CodePudding user response:

you can do this

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)

  • Related