0

I'm trying to remove an object that resides in an array of objects, based on the value that is located in an array inside that object.

The data structure that I have right now is like this:

[
   {name:['tutorial', 1, 'langkah'], value:"ABC"},
   {name:['tutorial', 2, 'langkah'], value:"DEF"},
   {name:['tutorial', 3, 'langkah'], value:"GHI"}
]

I would like to remove an object that has the name value of 1 in the name array.

I've tried to replicate the potential solution by using Object.keys found in here: remove object inside array inside an object based on id in javascript but I couldn't wrap my head around the different data structure.

1
  • 4
    if arr is your array, then arr.filter(obj => !obj.name.includes(1)) or if you want to check only 2nd element, then arr.filter(obj => obj.name[1] != 1) Commented Jul 2, 2021 at 6:51

1 Answer 1

1

You could use filter() and indexOf():

let main = [
   {name:['tutorial', 1, 'langkah'], value:"ABC"},
   {name:['tutorial', 2, 'langkah'], value:"DEF"},
   {name:['tutorial', 3, 'langkah'], value:"GHI"}
]

let ans = main.filter((x)=>{
  return x.name.indexOf(1)==(-1); //Returning true only for elements where 1 is not an element in name property array
});

Your original array stays as it is.

Note: There are no checks here, so this will fail if your array elements do not follow the same structure as you mentioned.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.