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)
Related
This question already has answers here:
Object copy using Spread operator actually shallow or deep?
(4 answers)
Closed 6 months ago.
I have a use case that I thought the Map object would be perfect for but there is confusing behaviour that appears to me as a bug, but Im after any information as to why this happens and possibly a solution to the behaviour.
For instance, say I have 2 objects:
const obj1 = { name: "John" };
const obj2 = { name: "Jane", age: 35 };
And I have defined and extra object for extra properties to add to both objects later:
const extProps = { gender: "unspecified", children: [] };
Create a new Map object and add the 2 objects:
const map = new Map();
map.set(obj1.name, obj1);
map.set(obj2.name, obj2);
Due to the objects being reference types I can assign the extra props like so:
Object.assign(obj1, { ...extProps });
Object.assign(obj2, { ...extProps });
Now I can get the values from the map using the keys like:
const johnObj = map.get("John");
const janeObj = map.get("Jane");
And the object have all the extra props like expected. The following statements update the individual objects in the map:
janeObj.gender = "female";
johnObj.age = 45;
Here is where the confusing behaviour I see is happening...
If I add an entry to the children array of either objects, it updates both
johnObj.children.push("jack");
obj2.children.push("jenny");
name: "John"
gender: "unspecified"
children: ["jack", "jenny"]
age: 45
name: "Jane"
age: 35
gender: "female"
children: ["jack", "jenny"]
What am I missing??
Like Konrad said in his comment, "arrays are also objects and are reference types".
The issue is that the spread operator (...) only goes on level deep, so for the array in extProps, is it not copied, it is the same one.
To solve this you can use a recursive function to "deep copy" an object.
Here is an example of a deep copy function:
const deepCopy = objIn => {
if (typeof objIn !== 'object' || objIn === null) return objIn;
let objOut = Array.isArray(objIn) ? [] : {};
for (const key in objIn) {
objOut[key] = deepCopy(objIn[key]);
}
return objOut;
}
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}))
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:
Destructuring object and ignore one of the results
(4 answers)
Closed 3 years ago.
I wanna to select all props but one from a javascript object but doing in elegant way using ES6, is this possible?
example:
const myObj = { prop1, prop2, prop3 }
const newObj = {
…myObject.remove(prop3)
}
then newObj should be { prop1, prop2}
if destruct I can select some, or all
const newObj = {
…myObject
}
const {prop1, prop2} = myObjct
but I dont know how to select all but one.
You can use the object rest syntax to assign all other properties to newObj, except those explicitly stated:
const myObj = { prop1: 1, prop2: 2, prop3: 3 }
const { prop1, ...newObj } = myObj
console.log(newObj)
This question already has answers here:
How to convert an Object {} to an Array [] of key-value pairs in JavaScript
(21 answers)
Closed 19 days ago.
if we create one object like
const userDetails={firstname:'karan',lastname:'khimani'}
then expected output like
[["firstname", "karan"], ["lastname", "khimani"]]
How did i convert this?
Use Object.entries:
const userDetails = { firstname: "karan", lastname: "khimani" };
const arr = Object.entries(userDetails);
console.log(arr);
I believe this is an ES7 feature - so if you need to support older browsers, use map with Object.keys:
var userDetails = { firstname: "karan", lastname: "khimani" };
var arr = Object.keys(userDetails).map(function(key) {
return [key, userDetails[key]]
});
console.log(arr);
So what you want to do is create an array, which contains keys and values as arrays.
You should have a look at Object.keys and Object.entries.
Soluce are below, but try to find it yourself first looking at the documentation of the functions I've given you.
const userDetails = {
firstname: 'karan',
lastname: 'khimani'
};
const transformed = Object.keys(userDetails).map(x => [x, userDetails[x]]);
console.log(transformed);
Why not always use Object.entries? Because It's not well supported on every browser.
const userDetails = {
firstname: 'karan',
lastname: 'khimani'
};
const transformed = Object.entries(userDetails);
console.log(transformed);