0

I have an array that looks something like this:

const arrayObj = [
 {
 id: 1,
 itemsList: [
 {
 name: "Paul",
 },
 {
 name: "Newman",
 },
 ],
 },
 {
 id: 2,
 itemsList: [
 {
 name: "Jack",
 },
 {
 name: "Man",
 },
 ],
 },
]

What I want is to filter the objects whose itemsList contain an object with the name of a certain value. For example, I want to be able to filter out an array with objects whose inner objects with names that contain "ul" (in this case the name Paul contains "ul"), it should give me an output as such:

const outputArray = [
 {
 id: 1,
 itemsList: [
 {
 name: "Paul",
 },
 {
 name: "Newman",
 },
 ]
 }
]

So far, I've only been able to filter out a simple flat array of objects with this function:

function filterByName(array: any, string: any) {
 return array.filter((obj: any) =>
 ["name"].some((key: any) =>
 String(obj[key]).toLowerCase().includes(string.toLowerCase())
 )
 );
}

but I don't know how to apply it to my case.

asked Aug 17, 2022 at 8:16
1

2 Answers 2

1

Here you can use the some method combined with the includes method

const arrayObj = [{
 id: 1,
 itemsList: [{
 name: "Paul",
 },
 {
 name: "Newman",
 },
 ],
 },
 {
 id: 2,
 itemsList: [{
 name: "Jack",
 },
 {
 name: "Man",
 },
 ],
 },
]
const getFilterArray = (name) => {
 return arrayObj.filter(obj => obj.itemsList.some(x => x.name.toLowerCase().includes(name.toLowerCase())))
}
console.log(getFilterArray("ul"))

answered Aug 17, 2022 at 8:21
Sign up to request clarification or add additional context in comments.

Comments

0
const result = arrayObj.filter(({ itemsList }) =>
 itemsList.some(({ name }) => name.toLowerCase().includes('ul')));

Can you try this?

answered Aug 17, 2022 at 8:33

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.