javascript - Merging Arrays of Objects by Key/Values -
i have 2 separate arrays of objects need merge based if specific key value matches. might make more sense after analyzing data:
array 1
let categories = [ { id: 5, slug: 'category-5', items: [] }, { id: 4, slug: 'category-4', items: [] }, { id: 3, slug: 'category-3', items: [] }, ]
array 2
let items = [ { id: 5, data: [{ title: 'item title', description: 'item description' }] }, { id: 5, data: [{ title: 'item title 2', description: 'item description 2' }] }, { id: 4, data: [{ title: 'item title 4', description: 'item description 4' }] }, ]
expected output
let mergedoutput = [ { id: 5, slug: 'category-5', items: [ { title: 'item title', description: 'item description' }, { title: 'item title 2', description: 'item description 2' } ] }, { id: 4, slug: 'category-4', items: [ { title: 'item title 4', description: 'item description 4' }, ] }, { id: 3, slug: 'category-3', items: [] }, ]
so....i need add array 2 array 1 if id's match. array 1 stay same, if array 2 matches, items property of array 1 (empty) replaced data property of array 2
i know pretty basic / , redundant question, can't find resources use case / object structure.
i able group arrays lodash -- if there similar solution library -- good! or direction suffice.
thanks in advance!
you can loop first array , use filter
objects same id current element , add items current object.
let categories = [ { id: 5, slug: 'category-5', items: [] }, { id: 4, slug: 'category-4', items: [] }, { id: 3, slug: 'category-3', items: [] }, ] let items = [ { id: 5, data: [{ title: 'item title', description: 'item description' }] }, { id: 5, data: [{ title: 'item title 2', description: 'item description 2' }] }, { id: 4, data: [{ title: 'item title 4', description: 'item description 4' }] }, ] categories.foreach(function(e) { var = items.filter(a => a.id == e.id).map(a => a.data); e.items = i; }) console.log(categories)
Comments
Post a Comment