How can I merge Object in Javascript? [duplicate] - javascript

This question already has answers here:
Merge two array of objects based on a key
(23 answers)
Closed 1 year ago.
This is two object. One is 'major'. Other one is 'marjorModel'.
const major = [
{
id: 1,
subject: 'math',
title: 'no good'
},
{
id: 2,
subject: 'science',
title: 'good'
}
]
const majorModel = [
{
id: 1,
amount: 23,
date: '2022-03-01'
},
{
id: 3,
amount: 26,
date: '2022-03-01'
}
]
and I want to merge new one
example)
const newObj = [
{
id: 1,
subject: 'math',
title: 'no good',
amount: 23,
date: '2022-03-01'
},
{
id: 2,
subject: 'science',
title: 'good',
amount: 26,
date: '2022-03-01'
}
]
I don't know how to merge different of other object.
please let me know!!

You can use reduce
major.reduce((acc, v, i) => {
acc.push({
...v,
...majorModel[i]
});
return acc;
}, []);

Related

JavaScript: Best way to check if duplicate value for a particular key exists in an array of objects [duplicate]

This question already has answers here:
How can I check if the array of objects have duplicate property values?
(15 answers)
Closed 2 months ago.
I have an array of objects, for example:
[
{
id: 1243,
name: "Cola",
isLocationAssign: true,
location: 8
},
{
id: 1243,
name: "Cola",
isLocationAssign: true,
qty: 30,
location: 8
}
]
In the above array of objects we have the same value for location. What would be the best way to find out if duplicate values for a particular key exist in an array of objects? I can't think past multiple loops
let array = [
{
id:1234,
name: "Cola",
isLocationAssign: true,
location: 8
},
{
id: 1234,
name: "Cola",
isLocationAssign: true,
qty: 30,
location: 8
},
{
id: 1235,
name: "Cola",
isLocationAssign: true,
qty: 30,
location: 8
},
{
id: 1235,
name: "Cola",
isLocationAssign: true,
qty: 30,
location: 7
}
]
let duplicatedIdsItems = array.filter(a => a.id === 1234);
console.log(duplicatedIdsItems)
var valueArr = duplicatedIdsItems.map(function(item){ return item.location });
var isDuplicate = valueArr.some(function(item, idx){
return valueArr.indexOf(item) != idx
});```

How can I map and Object with Arrays as values? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
How to loop through a plain JavaScript object with the objects as members
(28 answers)
Closed 1 year ago.
Given the following array of objects with dates in UTC:
const Arr = [
{
"name": "Person 1",
"date": "2021-02-28T14:00:00.000+0000"
},
{
"name": "Person 2",
"date": "2021-02-28T19:15:00.000+0000"
},
{
"name": "Person 3",
"date": "2021-04-04T18:30:00.000+0000"
},
{
"name": "Person 4",
"date": "2021-05-11T19:00:00.000+0000"
},
{
"name": "Person 5",
"date": "2021-05-12T18:45:00.000+0000"
},
{
"name": "Person 6",
"date": "2021-05-11T19:00:00.000+0000"
},
{
"name": "Person 7",
"date": "2021-05-23T15:00:00.000+0000"
}
];
I grouped the items by date using reduce as described in the below code:
const eventDate = {};
Arr.reduce((groupByDate, event) => {
const date = event.date.split('T')[0];
if (!groupByDate[date]) {
groupByDate[date] = [];
}
groupByDate[date].push(event);
return groupByDate;
}, {});
Getting an object grouped by date (as key) and an array of objects (as values):
{
'2021-02-28': [
{ name: 'Person 1', date: '2021-02-28T14:00:00.000+0000' },
{ name: 'Person 2', date: '2021-02-28T19:15:00.000+0000' }
],
'2021-04-04': [ { name: 'Person 3', date: '2021-04-04T18:30:00.000+0000' } ],
'2021-05-11': [
{ name: 'Person 4', date: '2021-05-11T19:00:00.000+0000' },
{ name: 'Person 6', date: '2021-05-11T19:00:00.000+0000' }
],
'2021-05-12': [ { name: 'Person 5', date: '2021-05-12T18:45:00.000+0000' } ],
'2021-05-23': [ { name: 'Person 7', date: '2021-05-23T15:00:00.000+0000' } ]
}
So my doubt here is how can I loop through that new object in order to get something like this?
(date in UTC will be formatted and get only the time)
2021-02-28:
name: Person 1 time: 14:00
name: Person 2 time: 19:15
2021-04-04:
name: Person 3 time: 18:30
2021-05-11:
name: Person 4 time: 19:00
name: Person 6 time: 19:00
2021-05-12:
name: Person 5 time: 18:45
2021-05-23:
name: Person 7 time: 15:00
Thanks in advance!
I would use Object.entries() or Object.keys() on the top level object to loop over it (for example using forEach() or any other looping method):
Object.entries(data).forEach(([key, items]) => {
console.log(key);
items.forEach(item => {
console.log("name:", item.name, "date:", item.date)
})
})
Playround
Perhaps something like this?
const obj = {
'2021-02-28': [
{ name: 'Person 1', date: '2021-02-28T14:00:00.000+0000' },
{ name: 'Person 2', date: '2021-02-28T19:15:00.000+0000' }
],
'2021-04-04': [{ name: 'Person 3', date: '2021-04-04T18:30:00.000+0000' }],
'2021-05-11': [
{ name: 'Person 4', date: '2021-05-11T19:00:00.000+0000' },
{ name: 'Person 6', date: '2021-05-11T19:00:00.000+0000' }
],
'2021-05-12': [{ name: 'Person 5', date: '2021-05-12T18:45:00.000+0000' }],
'2021-05-23': [{ name: 'Person 7', date: '2021-05-23T15:00:00.000+0000' }]
}
const newObj = {}
const newSubObj = {}
for (const [key, value] of Object.entries(obj)) {
newObj[key] = []
newSubObj[key] = []
for (const item of value) {
const date = new Date(item.date)
const subDate = item.date.substr(11, 5)
const hours = date.getUTCHours()
const minutes = date.getUTCMinutes()
newObj[key].push({ name: item.name, time: `${hours}:${minutes}` })
newSubObj[key].push({ name: item.name, time: subDate })
}
}
console.log(newObj, newSubObj)
Assuming you want to console.log() the result this is how I will do it:
const obj = {
'2021-02-28': [
{ name: 'Person 1', date: '2021-02-28T08:00:00.000+0000' },
{ name: 'Person 2', date: '2021-02-28T19:15:00.000+0000' }
],
'2021-04-04': [ { name: 'Person 3', date: '2021-04-04T18:30:00.000+0000' } ],
'2021-05-11': [
{ name: 'Person 4', date: '2021-05-11T19:00:00.000+0000' },
{ name: 'Person 6', date: '2021-05-11T19:00:00.000+0000' }
],
'2021-05-12': [ { name: 'Person 5', date: '2021-05-12T18:45:00.000+0000' } ],
'2021-05-23': [ { name: 'Person 7', date: '2021-05-23T15:00:00.000+0000' } ]
}
const printObj = (obj) => {
Object.keys(obj).forEach(key => {
console.log(`${key}:`);
obj[key].forEach(val => {
const currentDate = new Date(val.date);
const currentDateHours = (currentDate.getUTCHours() < 10 ? '0' : '') + currentDate.getUTCHours();
const currentDateMinutes = (currentDate.getUTCMinutes() < 10 ? '0' : '') + currentDate.getUTCMinutes();
console.log(`name: ${val.name} time: ${currentDateHours}:${currentDateMinutes}`);
})
});
}
printObj(obj);
Note: getUTCHours() and getUTCMinutes() will not show two digit number in case of a leading 0, I took it into consideration.

How to sort array of objects have date properties? [duplicate]

This question already has answers here:
How to sort an array of objects by date?
(4 answers)
Closed 2 years ago.
I have an array :
const arr = [
{ name: 'abc', date: '30/03/2014' },
{ name: 'cde', date: '30/03/2015' },
{ name: 'fgh', date: '20/04/2014' },
{ name: 'xyz', date: '17/09/2014' },
];
How can I sort this array so that the output would be like this:
const arr = [
{ name: 'cde', date: '30/03/2015' },
{ name: 'xyz', date: '17/09/2014' },
{ name: 'fgh', date: '20/04/2014' },
{ name: 'abc', date: '30/03/2014' },
];
// sort the array with date in latest first.
Using Array#sort with your own sorting comperator. For this split the dates and build with taht in the right sequence a new Date which can be compared.
const arr = [
{ name: 'abc', date: '30/03/2014' },
{ name: 'cde', date: '30/03/2015' },
{ name: 'fgh', date: '20/04/2014' },
{ name: 'xyz', date: '17/09/2014' },
];
arr.sort((a,b) => {
let tempA = a.date.split('/');
let tempB = b.date.split('/');
return ((new Date(tempB[2],tempB[1],tempB[0])) - (new Date(tempA[2],tempA[1],tempA[0])));
});
console.log(arr);

how to add nested object with new object [duplicate]

This question already has answers here:
Add new element to an existing object
(6 answers)
Closed 3 years ago.
Actually, I want to add hats object to clothing object, i don't want to change object to array of object.
Can anyone help me how to add hats in my scenario.
const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
{
id: 01,
name:'plain shirt',
},
{
id: 02,
name: 'stripe shirt',
},
],
},
tshirt: {
id: 2,
title: 't-shirt',
item: [
{
id: 03,
name: 'plain t-shirt',
},
{
id: 04,
name: 'stripe t-shirt',
}
],
},
}
const newClothing = {...clothing};
newClothing[{hats:{id:3, title:'hats', item:[{id:05, name:'blue hats'}]}}];
console.log(newClothing.hats);
This is the simplest way you can do it:
const newClothing = {...clothing, hats: { ...your hats object here } };
From what I understand, I don't think you need to do anything fancy here. Simply add a property as follows:
clothing.hats = {
id:3,
title:'hats',
item:[{id:05, name:'blue hats'}]
}
Use . notation to add the hats object
const clothing = {
shirts:{
id: 1,
title: 'shirts' ,
item: [
{
id: 01,
name:'plain shirt',
},
{
id: 02,
name: 'stripe shirt',
},
],
},
tshirt: {
id: 2,
title: 't-shirt',
item: [
{
id: 03,
name: 'plain t-shirt',
},
{
id: 04,
name: 'stripe t-shirt',
}
],
},
}
clothing.hats={id:3, title:'hats', item:[{id:05, name:'blue hats'}]};
console.log(clothing.hats);

Sum properties array of Objects [duplicate]

This question already has answers here:
Aggregating object values of JavaScript arrays?
(2 answers)
Closed 4 years ago.
I have an Array of objects, for example:
[{
name: 'mike',
id: 3312,
points: 2,
summary: 'example',
}, {
name: 'andrew',
id: 4123,
points: 1,
summary: 'example',
}, {
name: 'mike',
id: 0522,
points: 5,
summary: 'example',
}]
I need to sum the points for each person, the problem I´m facing is there are more than 50 different person names so I can´t do something like this
for (let i = 0; i < issues.length; i++) {
if (issues[i].name == 'mike') {
//////////////////////
}
}
Because the API in future can return a new Person.
You can reduce into an object indexed by name:
const input = [{
name: 'mike',
id: 3312,
points: 2,
summary: 'example',
},
{
name: 'andrew',
id: 4123,
points: 1,
summary: 'example',
},
{
name: 'mike',
id: 0522,
points: 5,
summary: 'example',
}];
const points = input.reduce((a, { name, points }) => (
Object.assign(a, { [name]: (a[name] || 0) + points })
), {});
console.log(points);
If you do not want to use reduce and keep things simple you can still use a forEach loop as below:
const input = [{
name: 'mike',
id: 3312,
points: 2,
summary: 'example',
},
{
name: 'andrew',
id: 4123,
points: 1,
summary: 'example',
},
{
name: 'mike',
id: 0522,
points: 5,
summary: 'example',
}];
var res = {};
input.forEach((obj) => {
res[obj.name] = res[obj.name] ? res[obj.name]+obj.points : obj.points;
});
console.log(res);

Categories