This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 2 years ago.
I am trying to convert a array of unique ids to a flat map of theses
const arr = [ { user1: 'val' }, { user2: 'val' } ]
and I want to convert to
{ user1: 'val', user2: 'val' }
How can I do this?
Using array.reduce
arr.reduce((obj, val) => ({...obj, ...val}))
Related
This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 5 months ago.
I call the function
getAllUsers() {
return this.http.get(this.url);
}
with:
this.UserService.getAllUsers().subscribe(res => {
console.log(res);
})
The output is:
[{id:1, name:'anna'}, {id:2, name:'john'}, {id:3, name:'victor'}]
but I would like to return an array of all names:
['anna', 'john', 'victor']
Does anyone have an idea how to do that?
this.UserService.getAllUsers().subscribe(res => {
const names = res.map(i => i.name)
console.log(names)
})
This question already has answers here:
Convert Array to Object
(46 answers)
Closed 12 months ago.
I need to construct API body for using in javascript fetch. The length of array is twenty or so and I need a loop.
I have an array of objects:
[
{
name:"x",lname:"y"
},
{
name:"x2",lname:"y2"
},
]
and this what I want to achieve:
{
"0":{
"name":"x",
"lname":"y"
},
"1":{
"name":"x2",
"lname":"y2"
},
}
This is raw in postman body:
Any guide and help would be appreciated.
Converting an Array to an Object is easily done with Array.reduce and using the index argument as the key of the properties:
const data = [
{name:"x",lname:"y"},
{name:"x2",lname:"y2"},
]
console.log(
data.reduce((acc, item, i) => ({...acc, [i]:item}) ,{})
)
Or shorter, as suggested by #CherryDT (in the comments below), which automatically converts the Array to an Object consisting of keys derived from the array's items' indices:
const data = [
{name:"x",lname:"y"},
{name:"x2",lname:"y2"},
]
console.log({...data})
Tip: If you want the keys indices to start from 1 and not 0, do:
console.log({...[,...data]})
This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 1 year ago.
I have a requirement wherein I get nested object keys in an array. I have an array of keys like
let keys = ["vehicleInformation", "VehicleBlock|1", "DriverAssociation|1", "DriverInvolvedAssociation"]
There is already a JSON data that is stored in a variable and I have to update a data object.
data['vehicleInformation']['VehicleBlock'][1]['DriverAssociation'][1]['DriverInvolvedAssociation'] = value;
Is there a way to achieve this in javascript?
Initial value of data:
data = {};
Expected result:
data = {
vehicleInformation: {
VehicleBlock: [
{},
{
DriverAssociation: [
{},
{DriverInvolvedAssociation: value},
],
},
],
},
};
keys = ["vehicleInformation", "VehicleBlock|1", "DriverAssociation|1", "DriverInvolvedAssociation"]
data = {
vehicleInformation: {
VehicleBlock: [
0,
{
DriverAssociation: [
0,
{},
],
},
],
},
};
let value = 42;
let keysToLast = keys.flatMap(key => key.split("|"));
let lastKey = keysToLast.pop();
keysToLast.reduce((a, e) => a[e], data)[lastKey] = value;
console.log(data);
Array keys are just strings like object keys, no reason to treat them differently (thus flatMap). Then just reduce to find the object whose property you need to set, and set it.
This question already has answers here:
How do I convert array of Objects into one Object in JavaScript?
(17 answers)
Convert Javascript array of objects into one object
(4 answers)
How to convert array of objects in one specific object?
(9 answers)
shortest way to create a comma separated object list [duplicate]
(2 answers)
Closed 2 years ago.
I have data that looks like this.
[
{
key: 'myKey'
value: 'myValue'
},
{
key: 'mySecondKey'
value: 'mySecondValue'
},
{
key: 'myThirdKey'
value: 'myThirdValue'
},
]
The amount of objects varies depending on how much values an account has set. I'm trying to return this in a format that looks like this
{
mykey: 'myValue'
mySecondKey: 'mySecondValue'
myThirdkey: 'myThirdValue'
}
Any advice on how I would go about doing this?
You can do something, like
const src = [{key:'myKey',value:'myValue'},{key:'mySecondKey',value:'mySecondValue'},{key:'myThirdKey',value:'myThirdValue'},],
result = Object.assign({}, ...src.map(o => ({[o.key]: o.value})))
console.log(result)
.as-console-wrapper{min-height:100%;}
You can use reduce for this:
const data = [{key:"myKey",value:"myValue"},{key:"mySecondKey",value:"mySecondValue"},{key:"myThirdKey",value:"myThirdValue"}];
const res = data.reduce((obj, {key, value}) => ({...obj, [key]: value}), {});
console.log(res);
Other answers work but I feel like they are a bit complicated, here's a simple for of loop:
const data = [
{
key: 'myKey',
value: 'myValue'
},
{
key: 'mySecondKey',
value: 'mySecondValue'
},
{
key: 'myThirdKey',
value: 'myThirdValue'
}
];
const result = {};
for(const {key, value} of data) {
result[key] = value;
}
console.log(result);
This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 5 years ago.
Suppose I have a data structure like this:
const list = [
{"hello": "world"},
{"goodbye": "cruel world"}
]
and I want to join it into:
{"hello": "world",
"goodbye": "cruel world"}
I can do it semi-elegantly like so:
const union = l.reduce((acc, o) => {
Object.keys(o).forEach((k) => acc[k] = o[k]);
return acc;
}, {})
But is there a more elegant way, perhaps built into the JS standard library?
You can do this with Object.assign() and ES6 spread syntax.
const list = [
{"hello": "world"},
{"goodbye": "cruel world"}
]
var obj = Object.assign({}, ...list);
console.log(obj)