使用javascript在对象数组中的值

时间:2016-11-09 22:07:52

标签: javascript arrays object

鉴于以下内容:

var myArray = [
  { 
    id: "3283267",
    innerArray: ["434","6565","343","3665"]
  },
  {
    id: "9747439",
    innerArray: ["3434","38493","4308403840","34343"]
  },
  {
    id: "0849374",
    innerArray: ["343434","57575","389843","38493"]
  }
];

我如何搜索 myArray 中的对象,以确定 innerArray 中是否存在字符串“38493”,然后返回一个具有该对象id的新数组....像这样:

var arrayWithIds = ["9747439", "0849374"];

3 个答案:

答案 0 :(得分:4)

您可以过滤数组,然后映射ID(使用ES6语法):

const arrayWithIds = myArray
  .filter(a => a.innerArray.includes('38493'))
  .map(a => a.id)

这是ES5替代方案:

var arrayWithIds = myArray
  .filter(function(a) {
    return ~a.innerArray.indexOf('38493');
  })
  .map(function(a) {
    return a.id;
  })

答案 1 :(得分:4)

使用Array.forEachArray.indexOf函数的简单解决方案:

var search =  "38493", 
    result = [];

myArray.forEach(function(o) {
     if (o.innerArray.indexOf(search) !== -1) this.push(o.id);   
}, result);

console.log(result);  // ["9747439", "0849374"]

答案 2 :(得分:0)

ES5方式,您也可以这样做。



var myArray = [
  { 
    id: "3283267",
    innerArray: ["434","6565","343","3665"]
  },
  {
    id: "9747439",
    innerArray: ["3434","38493","4308403840","34343"]
  },
  {
    id: "0849374",
    innerArray: ["343434","57575","389843","38493"]
  }
],
 searchData = "38493",
     result = myArray.reduce(function(p,c){
     	                       return ~c.innerArray.indexOf(searchData) ? (p.push(c.id),p) : p;
                             },[]);
console.log(result);