1

With an array like the following, how can I filter objects based on the texts.id? For example if I wanted to return this very same array without the texts object reffering to the id 123 how would I go about it? I have access to the id I want to filter out and also the name of the object where its located. I have been trying to figure this out but I am not sure this is doable with the filter method only. Thanks in advance to anyone that helps.

[
 0: Object {
  name: 'Name 1',
  texts[
   0: Obj{
    id: '123',
    body: 'test message'
   },
   1: Obj{
    id: '456',
    body: 'test message 2'
   }
  ]
 },

 1: Object {
  name: 'Name 2',
  texts[
   0: Obj{
    id: '789',
    body: 'test message3'
   },
   1: Obj{
    id: '101112',
    body: 'test message 4'
   }
  ]
 }
]
2
  • post your expected result as well Commented Dec 12, 2020 at 15:21
  • You probably need to use two loops: one to iterate over the outer array, and a second to iterate over the inner texts property of each member of the outer array. Commented Dec 12, 2020 at 15:23

2 Answers 2

1

It's not totally clear to me whether you want to remove the entire outer object where the texts array contains an object with a certain id (i.e: in your example, this would remove the whole object with name 'Name 1'), or if you just want to remove the object in the texts array which has a certain id (i.e: leaving the outer object, just removing the object in texts with id 123).

The former has been answered by @lissettdm above, but if it's the latter, you could do something like this:

const filter = "123";
entry.forEach(item => item.texts = item.texts.filter(text => text.id !== filter));
Sign up to request clarification or add additional context in comments.

3 Comments

Yes I want to remove the object inside texts (id and body) where the id equals the id I am searching for and return the rest of the array exactly as it was.
Hi there, what I've posted here should work then :) You can just replace entry by whatever the name of the variable containing your multi-dimensional array of objects is.
Yes that's what I did, thanks a lot mate, already accepted it as the correct answer.
1

Yes, it is possible using Array.prototype.filter() and Array.prototype.find()

const entry = [{name: "Name 1",texts: [{id: "123",body: "test message"},{id: "456",body: "test message 2"}]},{name: "Name 2",texts: [{id: "789",body: "test message3"},{id: "101112",body: "test message 4"}]}];
    
const filter= "123";
const output = entry.filter(item => item.texts.find(text=> text.id===filter));
    
console.log(output);

Comments

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.