2

I have the following nested objects in an array and i want to filter the result to return the id of a specific item.

const data = [
   {0: {id: 1, country: "SA", address: "IOXX"}},
   {1: {id:2, country: "SAP", name: "N", address: "IOP"}},
   {2: {id:3, country: "S", name: "NO", address: "I"}},
   {3: {id:4, country: "SXX", name: "NOI", address: "INDIA"}},
]

The solution i tried is returning null because of the nested objects structure i presume

var dataREsult =  data.filter(function(el) {
  return el.id == 4;
});

P.S: The structure of the data above is from the backend that iam working with.

I am a beginner with javascript. any help would be much appreciated.

8
  • 4
    Why is your data structured like that? Commented Feb 5, 2021 at 15:20
  • @adiga its the api response of a backend... Commented Feb 5, 2021 at 15:22
  • As a data structure that makes little sense. It's needlessly nested, and each inner-object lives at an inconsistent key (first one 0, second 1 etc) so you'd have to use Object.values() to get at it. If at all possible, normalise the structure. Commented Feb 5, 2021 at 15:22
  • @Mitya any example that you could show in terms of code? Commented Feb 5, 2021 at 15:23
  • 1
    If it is possible to change the data, please change your server code. That is ridiculous. Of course you could do return Object.values(el)[0].id === 4. But, it will be hard to access and update the state with that structure. Commented Feb 5, 2021 at 15:23

1 Answer 1

3

Use Object.values() inside Array.filter() callback.

const data = [
   {0: {id: 1, country: "SA", address: "IOXX"}},
   {1: {id:2, country: "SAP", name: "N", address: "IOP"}},
   {2: {id:3, country: "S", name: "NO", address: "I"}},
   {3: {id:4, country: "SXX", name: "NOI", address: "INDIA"}},
]

const result = data.filter(el => Object.values(el)[0].id === 4);

for(var i=data.length-1; i>=0; i--) {
  if(Object.values(data[i])[0].id === 4)
    data.splice(i, 1)
}


console.log(data);

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

7 Comments

thanks for the snippet, what would be the way to return only the id value, in case of you example 4. I intend to create a function out of it.
just same, you can make it as a function and return.
@JohnD why would you want to return the id value if you are filtering by id?
@adiga i am trying to delete the item with id = 4 in this example. I might be approaching it the wrong way but thats the ultimate goal.
I updated my answer, you can use array.forEach, and use array.splice() to delete the item. @JohnD
|

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.