how to compare two inner array of object from javascript

Viewed 89

I have two arrays of an object X and y, form x value array ["N","Y"], I need to filter the y array options value, based on that I need to return the y array, I had tried with this:

const x = [{"application":"Collect","attr":[{"name":"document","value":["N","Y"],"disabled":true}, {"name":"video","value":["Y"],"disabled":false}]}]
const y = [{"name":"document","options":[{"name":"Yes","value":"Y"},{"name":"No","value":"N"},{"name":"view", value:"view"}]}]

const iArr = x[0].attr.map(m => {
  m.value.map(o => {
    y.map(yl => {
      yl.options.filter(s => {
        if (o === s.value) {
          console.log(s)
        }
      })
    })
  })
})

console.log(iArr)

my output should be

const result = [{"name":"document","options":[{"name":"Yes","value":"Y"},{"name":"No","value":"N"}]}]
2 Answers

We can use Array.map here to alter the value of each element in y according to the attr details in x.

We filter each element.options in y by the corresponding attr value in x.

In this example, I'm presuming that the rules that apply to each element in y reside in the same attribute index , e.g. x[0].attr[index].

const x = [{"application":"Collect","attr":[{"name":"document","value":["N","Y"],"disabled":true}, {"name":"video","value":["Y"],"disabled":false}]}]
const y = [{"name":"document 1","options":[{"name":"Yes","value":"Y"},{"name":"No","value":"N"},{"name":"view", value:"view"}]},
  {"name":"document 2","options":[{"name":"Yes","value":"Y"},{"name":"No","value":"N"},{"name":"view", value:"view"}]}]

const result = y.map((element, index) => {
    let res = { ... element };
    res.options = element.options.filter(option => x[0].attr[index].value.includes(option.value));
    return res;
}); 

console.log("Result:",result);

If you just have one element in the x array then you could to this

const x = [{
  "application": "Collect",
  "attr": [{
    "name": "document",
    "value": ["N", "Y"],
    "disabled": true
  }]
}]

const y = [{
  "name": "document",
  "options": [{
    "name": "Yes",
    "value": "Y"
  }, {
    "name": "No",
    "value": "N"
  }, {
    "name": "view",
    "value": "view"
  }]
}]



const result = y.map(z => ({
  ...z,
  options: z.options.filter(k => x[0].attr[0].value.includes(k.value))
}));
console.log(result)

Related