简体   繁体   English

如何过滤 javascript 中数组内的嵌套对象

[英]how to filter an nested objects inside an array in javascript

I have the following nested objects in an array and i want to filter the result to return the id of a specific item.我在数组中有以下嵌套对象,我想过滤结果以返回特定项目的 id。

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我尝试的解决方案是返回 null 因为我认为嵌套对象结构

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

PS: The structure of the data above is from the backend that iam working with. PS:上面的数据结构来自我正在使用的后端。

I am a beginner with javascript.我是 javascript 的初学者。 any help would be much appreciated.任何帮助将非常感激。

Use Object.values() inside Array.filter() callback.Array.filter()回调中使用Object.values()

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM