Merge objects by key with concatenating all other properties into arrays [duplicate] - javascript

This question already has answers here:
Grouping an array of objects using a key in Javascript
(3 answers)
Group array items using object
(19 answers)
How to group array of objects by certain property values
(5 answers)
Closed 17 days ago.
I have an array of objects:
[
{department: 'IT', employee: 'Niall', position: 'UI developer'},
{department: 'FINANCE', employee: 'Jimmy', position: 'Financial Analyst'},
{department: 'IT', employee: 'John', position: 'web designer'},
{department: 'FINANCE', employee: 'William', position: 'Consultant'},
{department: 'HEALTH', employee: 'Andy', position: 'doctor'}
]
I want to merge the objects by department and create a new object with two properties: the key by which we did the merge, and a 'details' property which is an array of objects of all the other properties by employee.
The desired output is :
[
{
'department' : 'IT',
'details': [ {'employee': 'Niall', 'position': 'UI developer'},
{'employee': 'John', 'position': 'web designer'}]
},
{
'department' : 'FINANCE',
'details': [ {'employee': 'Jimmy', 'position': 'Financial Analyst'},
{'employee': 'William', 'position': 'Consultant'}]
},
{
'department' : 'FINANCE',
'details': [ {'employee': 'Andy', 'position': 'doctor'}]
}
]

const data = [{"department":"IT","employee":"Niall","position":"UI developer"},{"department":"FINANCE","employee":"Jimmy","position":"Financial Analyst"},{"department":"IT","employee":"John","position":"web designer"},{"department":"FINANCE","employee":"William","position":"Consultant"},{"department":"HEALTH","employee":"Andy","position":"doctor"}]
console.log(Object.values(data.reduce((a,{department:d, ...o})=>
((((a[d]??={department:d}).details??=[]).push(o)),a),{})))

Related

JavaScript: how to filter a nested Object based on a string array? [duplicate]

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 3 months ago.
I am a newbie to JavaScript. I have now a nested Object:
const fruitList = [
{ fruit: {id: '1-1', fruit_name: 'Apple'},
location: {id: '2-1', location_name: 'USA'}
},
{
fruit: {id: '1-2', fruit_name: 'Banana'},
location: {id: '2-2', location_name: 'UK'}
},
{
fruit: {id: '1-3', fruit_name: 'Orange'},
location: {id: '2-1', location_name: 'USA'}
}
];
and a string array:
let keywords = ['Apple', 'Banana'];
I am trying to filter the nested Object based on the above string array and the expected outpust is :
output =[
{ fruit: {id: '1-1', fruit_name: 'Apple'},
location: {id: '2-1', location_name: 'USA'}
},
{
fruit: {id: '1-2', fruit_name: 'Banana'},
location: {id: '2-2', location_name: 'UK'}
}
];
I already tried:
const filteredFruit = fruitList.filter(({item})=>
item.fruit?.fruit_name.every(ele => keywords.includes(ele))
)
but it didn't work. I also checked all the similar questions on the Stackoverflow, but still could not find a way to solve it. Thank you very much for your help!
You were close.
item isn't a property of the object being iterated on so you can't destructure it.
You need to swap around your condition to check to see if the keywords array includes the fruit name.
const fruitList=[{fruit:{id:"1-1",fruit_name:"Apple"},location:{id:"2-1",location_name:"USA"}},{fruit:{id:"1-2",fruit_name:"Banana"},location:{id:"2-2",location_name:"UK"}},{fruit:{id:"1-3",fruit_name:"Orange"},location:{id:"2-1",location_name:"USA"}}];
const keywords = ['Apple', 'Banana'];
const filteredFruit = fruitList.filter(item =>
keywords.includes(item.fruit.fruit_name)
);
console.log(filteredFruit);

Javascript retrieving data from an array [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 1 year ago.
I'm failing to achieve something very simple. I can't retrieve specific data of an array. I've browsed through the documentation and similar threads on stack overflow but none seem to work.
For example:
[
{
id: 123,
name: 'Name1',
},
{
id: 456,
name: 'Name2',
},
{
id: 789,
name: 'Name3',
},
]
How could I possibly get all 'name' variables from each {} ?
You can use forEach or map to get a specific property from the list of objects:
let data = [{
id: 123,
name: 'Name1',
},
{
id: 456,
name: 'Name2',
},
{
id: 789,
name: 'Name3',
},
]
let names = []
data.forEach(element => names.push(element.name))
console.log(names)
names = data.map(element => element.name)
console.log(names)
You simply need to use .map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
The following code should do the job.
const names = yourArray.map(e=> e.name)

How to merge two arrays to an object? [duplicate]

This question already has answers here:
Create an object from an array of keys and an array of values
(9 answers)
Closed 1 year ago.
I have two arrays with the same length.
array1 = ['title', 'details', 'price', 'discount'];
array2 = ['product name', 'product details', 200, 20];
Want to convert them into one object like following
newObject = {
title: 'product name',
details: 'product details',
price: 200,
discount: 20
}
How to do that?
You can create the pairs using Array#map and convert the result into the object using Object#fromEntries:
const
array1 = ['title', 'details', 'price', 'discount'],
array2 = ['product name', 'product details', 200, 20];
const newObject = Object.fromEntries(
array1.map((e,i) => ([e, array2[i]]))
);
console.log(newObject);

Calculate array subtotals by category [duplicate]

This question already has answers here:
Better way to sum a property value in an array
(20 answers)
ES6 Sum by object property in an array
(4 answers)
Closed 2 years ago.
I have an array:
const expenses = [
{ key: '1', sum: '100', category: 'car' },
{ key: '2', sum: '200', category: 'food'},
{ key: '3', sum: '300', category: 'furniture'},
{ key: '4', sum: '400', category: 'food'},
{ key: '5', sum: '700', category: 'car' },
]
How can I get new array or objects with total amount of certain categories?
Like
newArray = [
{category: 'car' totalSum:800},
{category: 'food' totalSum:600},
{category: 'furniture' totalSum:300}
]
Thanks for any suggestions.
Use Array.prototype.reduce():
const expenses = [{key:'1',sum:'100',category:'car'},{key:'2',sum:'200',category:'food'},{key:'3',sum:'300',category:'furniture'},{key:'4',sum:'400',category:'food'},{key:'5',sum:'700',category:'car'},],
result = Object.values(expenses.reduce((r, {category, sum}) =>
(r[category] = {category, totalSum: (r[category]?.totalSum || 0)+ +sum}, r), {}))
console.log(result)
.as-console-wrapper{min-height:100%;}

How to map an array of objects by a given field? [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 3 years ago.
I have an array of objects:
let tempArray = [
{
id: '1',
name: 'Tom',
age: 11
},
{
id: '2',
name: 'Jerry',
age: 13
}
...
]
How can I create a new array that would contain only name fields from all objects of the tempArray array?
Trying using map()
let tempArray = [
{
id: '1',
name: 'Tom',
age: 11
},
{
id: '2',
name: 'Jerry',
age: 13
}
]
const res = tempArray.map(i => i.name)
console.log(res)

Categories

Resources