Merging objects from array with the same key value
You could use reduce
with Object.keys
to do that.
var arr = [
{id: 1, tech_id:11, action: 'swim'},
{id: 2, tech_id:11, action: 'run'},
{id: 3, tech_id:22, action: 'climb'},
{id: 4, tech_id:22, action: 'swim'},
{id: 5, tech_id:11, action: 'jump'},
]
let mergeObj = arr.reduce((p, c) => {
const {tech_id, ...otherData} = c;
if (!(tech_id in p)) {
p[tech_id] = {
data: []
}
}
p[tech_id].data.push(otherData)
return p
}, {})
mergeObj = Object.keys(mergeObj).map(key => {
return {
tech_id: key,
data: mergeObj[key].data
}
})
console.log(mergeObj);
group the object in array by name
You can use forEach()
for this.
let obj = [
{
name: "a",
quantity: 2
},
{
name: "b",
quantity: 4
},
{
name: "c",
quantity: 88
}
]
let obj2 = [
{
name: "a",
quantity: 2
}
]
obj.forEach((element)=>{
obj2.forEach((e)=>{
if(element.name == e.name){
element.quantity = element.quantity+e.quantity
}
})
})
console.log(obj);
Merge two arrays of objects with the same keys in JavaScript
Your third try [arr1, arr2]
was really close to a right answer, you can use the new spread syntax (...)
to concat the arrays by doing to following:
const arr1 = [{ label: "one", value: "one", type: "arr1" }];
const arr2 = [{ label: "two", value: "two", type: "arr1" }];
console.log([...arr1, ...arr2]);
Related Topics
How to Clear All Input Fields in Bootstrap Modal When Clicking Data-Dismiss Button
Node.Js MySQL Query in a for Loop
How to Format Numbers in Vuejs
Reactjs - Multiple If Conditions Inside Map Function
Access a Variable Outside of .Then Function
How to Highlight Parts of an Imagemap on Mouseover
How to Redirect Url After Login Successful Via Ajax Call in PHP
How to Show a Confirm Message Before Delete
React Router Dom Returns a Blank Page When Going to a Particular Route
Blob Download Is Not Working in Ie
How to Combine First Name and Last Name in JavaScript
Vuejs Error, Invalid Prop: Type Check Failed for Prop. Expected Date, Got Number With Value
Ios Safari/Chrome - Unwanted Scrolling When Focusing an Input Inside the Modal
Error Ts2739: Type '{}' Is Missing the Following Properties from Type
How to Disable Button After (Click) in Angular
How to Display the Entire Object in Console in React Native
How to Add Button on Each Row in Datatable
Bootstrap Button Drop-Down Inside Responsive Table Not Visible Because of Scroll