简体   繁体   English

查询具有数组的对象(没有第三方脚本)

[英]Query objects with an array (without 3rd party script)

How can you query an object with an array? 如何使用数组查询对象?

var myArray = ['A','C']

Using myArray, how can I get a returned array with ['1','3'] out of the following (previously JSON object) (without using a third party query script -- unless it's jQuery :) 使用myArray,如何从以下(先前为JSON对象)中返回['1','3']的返回数组(不使用第三方查询脚本-除非是jQuery :)

[ { "property1": "1", 
    "property2": "A"
   },
  { "property1": "2", 
    "property2": "B"
   },
  { "property1": "3", 
    "property2": "C"
   } ]

You could a nested loop: 您可以嵌套循环:

var myArray = ['A','C'];
var json = [{ 
    'property1': '1', 
    'property2': 'A'
}, { 
    'property1': '2', 
    'property2': 'B'
}, { 
    'property1': '3', 
    'property2': 'C'
}];

var result = new Array();
for (var i = 0; i < myArray.length; i++) {
    for (var j = 0; j < json.length; j++) {
        if (json[j].property2 === myArray[i]) {
            result.push(json[j].property1);
        }
    }
}

// at this point result will contain ['1', '3']

You can walk the array like this: 您可以像这样遍历数组:

var json = [ { "property1": "1", 
    "property2": "A"
   },
  { "property1": "2", 
    "property2": "B"
   },
  { "property1": "3", 
    "property2": "C"
   } ];

var myArray = ['A', 'C']; // Here is your request
var resultArray = []; // Here is the container for your result

// Walking the data with an old-fashioned for loop
// You can use some library forEach solution here.
for (var i = 0, len = json.length; i < len; i++) {
    var item = json[i]; // Caching the array element

    // Warning! Not all browsers implement indexOf, you may need to use a library
    // or find a way around
    if (myArray.indexOf(item.property2) !== -1) {
        resultArray.push(item.property1);
    }
}

console.log(resultArray);

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

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