通过匹配值组合对象数组

时间:2019-05-21 21:43:32

标签: javascript ajax

我想合并两个对象数组,以使其更易于以HTML显示。该函数应在arr1中找到名为“ id”的键,在arr2中找到“ source”的键的匹配值。看起来是这样的:

   let arr1 = [
   {id = 1,
   name = "Anna"},

   {id = 2,
   name = "Chris"}
   ]

   let arr2 = [
   {childName = "Brian",
   {source = 1}},
   {childName = "Connie",
   {source = 2}}
   {childName = "Dory",
   {source = 1}}
   ]

我尝试了不同的方法,最好的方法是在数组上使用forEach和filter。我正在尝试在arr1对象中设置一个名为“儿童”的新属性。

  arr1.forEach(el => el.children = arr2.filter(checkMatch));

            function checkMatch(child){
                for(let i=0;i<arr1.length;i++){
                    child.childName.source === arr1[i].id
                }
            }

这会导致在第一个对象中添加适当的子代(Anna现在有Brian和Dory),这是正确的,但是它也将相同的子代添加到了第二个对象(因此Chris也有Brian和Dory)。 我的错在哪里?我猜想循环无法按我希望的方式工作,但是我不知道哪个循环以及如何发生。

4 个答案:

答案 0 :(得分:0)

由于用于创建arr1和arr2对象的语法无效,因此我尝试猜测对象的结构。

let arr1 = [
  {
    id: 1,
    name: "Anna"
  },
  {
    id: 2,
    name: "Chris"
  }
];

let arr2 = [
  {
    childName: "Brian",
    source: 1
  },
  {
    childName: "Connie",
    source: 2
  },
  {
    childName: "Dory",
    source: 1
  }
];

arr2.map((child) => {
  for (let parent of arr1) {
    if (parent.id == child.source) {
      if (!parent.children) {
        parent.children = [];
      }
      parent.children.push(child);
    }
  }
});

console.log(arr1);

答案 1 :(得分:0)

您的JSON出现问题,但我整理了一下,这里是使用mapfilter的选项

const arr1 = [{
    id: 1,
    name: "Anna"
  },
  {
    id: 2,
    name: "Chris"
  }];

const arr2 = [{
    childName: "Brian",
    parent: {
      source: 1
    }
  },
  {
    childName: "Connie",
    parent: {
      source: 2
    }
  },
  {
    childName: "Dory", 
    parent: {
      source: 1
    }
  }];

let merge = arr1.map(p => {
  p.children = arr2.filter(c => c.parent.source === p.id).map(c => c.childName);
  return p;
});

console.log(merge);

答案 2 :(得分:0)

您的json有一些您应该使用的问题

  

代替

  

=

还有一些花括号使结构不正确,但是我想在这里要做的是用主题的childNames填充children子数组,这是我的方法:

     var json = 
        [
           {
           "id" : 1,
           "name" : "Anna"
           },
           {
           "id" : 2,
           "name" : "Chris"
           }
          	 ];
             
         var subJson = [
           {
           "childName" : "Brian",
           "source" : 1
           },
           {
           "childName" : "Connie",
           "source" : 2
           },
           {"childName" : "Dory",
           "source" : 1
           }
           ];
        
        var newJson = [];
        $.each(json,function(index1,item){
        newJson.push({"id":item.id,"name":item.name, "children": []});
        	$.each(subJson,function(index2,subitem){
        	if(subitem.source == item.id){
          newJson[newJson.length - 1].children.push({"childName":subitem.childName}) ;
          }
          })
        })
        
        console.log(newJson);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

希望有帮助

答案 3 :(得分:-1)

以下使用Map来存储和方便查找父母。

const parents = [
  {
    id: 1,
    name: "Anna"
  },
  {
    id: 2,
    name: "Chris"
  }
]

const children = [
  {
    childName: "Brian",
    source: 1
  },
  {
    childName: "Connie",
    source: 2
  },
  {
    childName: "Dory",
    source: 1
  }
]

// Create a map for easy lookup of parents.
const parentMap = new Map()

// Add parents to the map, based on their id.
parents.forEach(parent => parentMap.set(parent.id, parent))

// Add children to their parents.
children.forEach((child) => {
  // Get the parent from the map.
  const parent = parentMap.get(child.source)

  // Handle parent not found error.
  if (!parent) { return console.error('parent not found for', child.childName)}

  // Create the children array if it doesn't already exist.
  parent.children = parent.children || []

  // Add the child to the parent's children array.
  parent.children.push(child)
})

// Output the result.
Array.from(parentMap).forEach(parent => console.log(parent[1]))

结果:

{ 
  id: 1,
  name: 'Anna',
  children: [ 
    { childName: 'Brian', source: 1 },
    { childName: 'Dory', source: 1 } 
  ] 
}
{ 
  id: 2,
  name: 'Chris',
  children: [ 
    { childName: 'Connie', source: 2 } 
  ] 
}