Объединение массивов объектов путем сопоставления значений - PullRequest
0 голосов
/ 22 мая 2019

Я хочу объединить два массива объектов, чтобы мне было легче отображать их в HTML. Функция должна найти совпадающие значения ключей, называемых «id» в arr1 и «source» в 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}}
   ]

Я пробовал разные подходы, лучший из которых использовал forEach и filter для массивов. Я пытаюсь установить новое свойство в объектах arr1, которое называется "children".

  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
                }
            }

И это приводит к добавлению подходящих потомков к первому объекту (теперь у Анны есть Брайан и Дори), так что это правильно, но он также добавляет тех же потомков ко второму объекту (поэтому у Криса также есть Брайан и Дори). Где здесь моя ошибка? Я предполагаю, что цикл не работает так, как я хочу, чтобы он работал, но я не знаю, какой и как это происходит.

Ответы [ 4 ]

0 голосов
/ 22 мая 2019

У вашего json есть некоторые проблемы, которые вы должны использовать

:

вместо

=

Также некоторые фигурные скобки делают структуру некорректной, но я думаю, что вы хотите здесь заполнить дочерний подмассив childNames субъекта, вот мой подход:

     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>

Надеюсь, это поможет

0 голосов
/ 22 мая 2019

Были проблемы с вашим JSON, но я привел в порядок и вот вариант с использованием map и filter

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);
0 голосов
/ 22 мая 2019

Ниже используется 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 } 
  ] 
}
0 голосов
/ 22 мая 2019

Поскольку ваш синтаксис для создания объектов 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);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...