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.
Advertisement
Answer
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);