0

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?

1
  • "I don't have any code to show" is not not the way to ask a question with a specific problem (read: How to Ask). Commented Jun 11, 2022 at 8:44

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

As a beginner, don't get engaged with fancy Array methods and use simple loops. 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.

1 Comment

Why should they not "get engaged with fancy Array methods"?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.