Home > Blockchain >  Return only the matched objects from multiple strings in a multidimensional array using Javascript
Return only the matched objects from multiple strings in a multidimensional array using Javascript

Time:03-29

I currently have 2 arrays. One is a flat array containing multiple strings and the other is a nested array. I am trying to return my nested array with only the objects that match the strings from my first array. What I am currently running into is my whole array is being returned if there is just one match oppose to just the matched object.

JS:

const rootIds = ["18828861", "15786287", "13435676"]
const filtData = [
    {
      year: "2022",
      awards: [
        {
          list: [
            {
              rootId: "18828861",
              name: "Globe",
            },
            {
              rootId: "15786222",
              name: "Golden"
            },
          ],
        },
      ],
    },
    {
      year: "2021",
      awards: [
        {
          list: [
            {
              rootId: "15786223",
              name: "Car",
            },
            {
              rootId: "13435676",
              name: "Red",
            },
          ],
        },
        {
          list: [
            {
              rootId: "15786287",
              name: "Black",
            },
            {
              rootId: "1578622",
              name: "Blue",
            },
          ],
        },
      ],
    },
];
const res = rootIds.map((a) => a);
const findIds = filtData.map(obj => obj.awards.filter(( { list }) => list.find(o => rootIds.includes(o.rootId))));
console.log("filtData====", findIds)

Desired output would be:

"filtData====", [[{
  list: [{
  name: "Globe",
  rootId: "18828861"
}]
}], [{
  list: [{
  name: "Red",
  rootId: "13435676"
}]
}, {
  list: [{
  name: "Black",
  rootId: "15786287"
}]
}]]

JsFiddle of not working demo: https://jsfiddle.net/hb7ej5sg/

CodePudding user response:

Found the cause at:

const findIds = filtData.map(obj => obj.awards.filter(( { list }) => list.find(o => rootIds.includes(o.rootId))));

Since you are using #filter on obj.awards array instead of #map and #find on list instead of #filter, you are getting the whole array from obj.awards[].list.

Using correct methods as follow would fix the issue:

const findIds = filtData.map(obj =>
    obj.awards.map(( { list }) =>
        list.filter(o => rootIds.includes(o.rootId))
    )
);
  • Related