How do I merge array of Objects but unshift array in JavaScript -
i merge these 2 array of objects urls
use unshift merge arrays instead of replacing.
here's example
var arr1 = [{ "keyword": "name", "score": 0.8992112752974006, "urls": ["url1"], "ids": ["5748bf9ab58adb2f614da195"] }, { "keyword": "name1", "score": 0.39953909596222775, "urls": ["url2"], "ids": ["5743260055f979a31fa98971"] }, { "keyword": "name3", "score": 0.4960953181766197, "urls": ["url4"], "ids": ["58c04cd5208b4945c3920cad"] }, { "keyword": "name4", "score": 0.3337163443410707, "urls": ["url5"], "ids": ["573628c38e32eeb039377f7e"] }]; var arr2 = [{ "keyword": "name", "score": 0.8992112752974006, "urls": ["url6"], "ids": [""] }, { "keyword": "name1", "score": 0.39953909596222775, "urls": ["url7"], "ids": [""] }]
i result
[{ "keyword": "name", "score": 0.8992112752974006, "urls": ["url6", "url1"], "ids": ["5748bf9ab58adb2f614da195"] }, { "keyword": "name1", "score": 0.39953909596222775, "urls": ["url7", "url2"], "ids": ["5743260055f979a31fa98971"] }, { "keyword": "name3", "score": 0.4960953181766197, "urls": ["url4"], "ids": ["58c04cd5208b4945c3920cad"] }, { "keyword": "name4", "score": 0.3337163443410707, "urls": ["url5"], "ids": ["573628c38e32eeb039377f7e"] }];
here's attempt result replace array of urls;
var a3 = arr1.concat(arr2).reduce((acc, x) => { acc[x.keyword] = object.assign(acc[x.keyword] || {}, x); return acc; }, {}); console.log(a3);
it urls
merged. other values overridden.
you use map
collecting objects same keyword
, update if necessary. solution works arbitrary count of arrays.
var array1 = [{ keyword: "name", score: 0.8992112752974006, urls: ["url1"], ids: ["5748bf9ab58adb2f614da195"] }, { keyword: "name1", score: 0.39953909596222775, urls: ["url2"], ids: ["5743260055f979a31fa98971"] }, { keyword: "name3", score: 0.4960953181766197, urls: ["url4"], ids: ["58c04cd5208b4945c3920cad"] }, { keyword: "name4", score: 0.3337163443410707, urls: ["url5"], ids: ["573628c38e32eeb039377f7e"] }], array2 = [{ keyword: "name", score: 0.8992112752974006, urls: ["url6"], ids: [""] }, { keyword: "name1", score: 0.39953909596222775, urls: ["url7"], ids: [""] }], map = new map, result = [], fn = => { if (map.has(a.keyword)) { map.get(a.keyword).urls.unshift(...a.urls); return; } map.set(a.keyword, a); result.push(a); }; [array1, array2].foreach(a => a.foreach(fn)); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Comments
Post a Comment