Home > Blockchain >  How to determine whether an array object has a value, and then return the array of objects with this
How to determine whether an array object has a value, and then return the array of objects with this

Time:06-11

How to determine whether an array object has a value, and then return the array of objects with this value. Because I'm a novice, I tried to write it, but I didn't, give an example:

const menu = [
  {
    title: "one",
    children: [{name: "hello"}, {name: "bye"}],
  },{
    title: "two",
    children: [{name: "good"}, {name: "bad"}],
  },
]

Assume input "bad", the result should be:

menu = [
  {
    title: "two",
    children: [{name: "good"}, {name: "bad"}],
  }
]

How to do it?

CodePudding user response:

Just loop through the array and then filter each element and its children like so:

const menu=[{title:"one",children:[{name:"hello",},{name:"bye",},],},{title:"two",children:[{name:"good",},{name:"bad"}]}];

const filterName = toFilter => {
  return menu.filter(({ children }) => {
    return children.some(({ name }) => name == toFilter);
  });
};

console.log(filterName("bad"));
console.log(filterName("good"));
console.log(filterName("neither"));
.as-console-wrapper { max-height: 100% !important; top: auto; }

CodePudding user response:

Don't get engaged with fancy Array methods. Try to use a for loop to loop over the menu array. Then for each item, loop over children property of the object. If name key matches with your desired output, you can push the whole object in your answer array:

const menu = [
      {
        title: "one",
        children: [
          {
            name: "hello",
          },
          {
            name: "bye",
          },
        ],
      },
      {
        title: "two",
        children: [
          {
            name: "good",
          },
          {
            name: "bad",
          },
        ],
      },
]
let ans = [];
for(let i = 0 ; i < menu.length;i  ){
if(menu[i].children){
  for(let j = 0 ; j < menu[i].children.length; j  ){
    if(menu[i].children[j].name === 'bad') ans.push(menu[i]);
  }
}
}

console.log(ans);

NOTE: The above assumes children is an array.

  • Related