如何比较两个对象数组

时间:2017-03-27 12:54:02

标签: javascript arrays javascript-objects

嗨我有两个数组比较两者,具体取决于常见的fq_id

var array1 =[
  {"description":" Virat Kohli","fq_id":156},{"description":" Lokesh Rahul","fq_id":156},{"description":"Chateshwar Pujara","fq_id":156},{"description":"Ajinke Rahane","fq_id":156}]

var array2 = [
  {"ans_description":"who is better?","fq_id":156}]
匹配fq_id后

结果数组应如下

result = [{
description:who is better?,
options:["Virat Kohli","Lokesh Rahul","Chateshwar Pujara","Rahane"]
}]

2 个答案:

答案 0 :(得分:1)

var array1 =[
  {"description":" Virat Kohli","fq_id":156},{"description":" Lokesh Rahul","fq_id":146},{"description":"Chateshwar Pujara","fq_id":157},{"description":"Ajinke Rahane","fq_id":156}]

var array2 = [
  {"ans_description":"who is better?","fq_id":156}]

var result = [{'description':array2[0].ans_description, 'options':[]}]

for(var i = 0; i<array1.length; i++) {
 if(array1[i].fq_id === array2[0].fq_id){ 
   result[0].options.push([array1[i].description])
 }
}

答案 1 :(得分:0)

您可以将Array#mapArray#filter用于包含已过滤项目的新对象。

简易版

&#13;
&#13;
UITabBarController
&#13;
&#13;
&#13;

版本为Map

&#13;
&#13;
var array1 = [{ description: "Virat Kohli", fq_id: 156 }, { description: "Lokesh Rahul", fq_id: 156 }, { description: "Chateshwar Pujara", fq_id: 156 }, { description: "Ajinke Rahane", fq_id: 156 }],
    array2 = [{ ans_description: "who is better?", fq_id: 156 }],
    result = array2.map(a => ({
        description: a.ans_description,
        options: array1.filter(b => a.fq_id === b.fq_id).map(a => a.description)
    }));

console.log(result);
&#13;
&#13;
&#13;