This question already has answers here:
How can I merge properties of two JavaScript objects dynamically?
(69 answers)
Closed 4 years ago.
I have 2 objects, and I need to add one object to the other object.
var loc = {
leftArray: [],
topArray: [],
bottomArray: [],
rightArray: []
}
var obj = {
id: "ce",
icon: "logo/image.png",
name: "CE",
type: "type2",
version: 3.4
}
var obj = {
id: "ce",
icon: "logo/image.png",
name: "CE",
type: "type2",
version: 3.4,
leftArray: [],
topArray: [],
bottomArray: [],
rightArray: []
}
Is there any simple way to do this?
You can do it with Object.assign();
obj = Object.assign(obj, loc);
or just
Object.assign(obj, loc);
as T.J. Crowder proposed in his comment.
you can merge them using Spread syntax like
let objOne = { a: 'hi' }
let objTwo = { b: 'hello' }
let objOneAndTwo = { ...objOne, ...objTwo }; // { a: 'hi', b: 'hello' }
or by using Object assign:
let objOneAndTwo = Object.assign({}, a, b)
note that using this way if your objects would have properties with the same name priority will be with the most right object (in this example objectTwo)
additional info:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
Related
This question already has answers here:
Flatten array with objects into 1 object
(12 answers)
Closed 1 year ago.
I have an array of objects in this shape;
const objectsArray = [{ projects: [] }, { components: [] }];
I want to merge it into a single object like this;
const mergedObject={ projects: [], components: [] }
Is there a better way of doing it other than this:
Object.keys(objectArray).map(key=>objectArray[key]).reduce((old,item)=>(
{...old,...item}
),{})
This might be a bit simpler:
const objectsArray = [{ projects: [1,2,3] }, { components: [4,5,6] }];
let mergedObjects
objectsArray.forEach(obj => mergedObjects = { ...mergedObjects, ...obj})
console.log(mergedObjects)
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)
Closed 3 years ago.
This is my array format
let array = [
0: {
key:"name",
value: "John"
},
1: {
key:"age",
value:25
},
2: {
key:"job",
value:"software engineer"
},...
];
Change this array to object in given below format
{
name: "John",
age: 27,
job: "software engineer"
}
You can achieve it using forEach on the array.
Give this a try:
const array = [{
key: "name",
value: "John"
}, {
key: "age",
value: 25
}, {
key: "job",
value: "software engineer"
}];
const expected = {};
array.forEach(item => expected[item.key] = item.value);
console.log(expected);
You can use Array.prototype.reduce() to do this:
let array = [
{
key:"name",
value: "John"
},
{
key:"age",
value:25
},
{
key:"job",
value:"software engineer"
}
];
let result = array.reduce((a,b) => {
a[b.key] = b.value;
return a;
}, {});
console.log(result);
All you need to do is to loop over the array using forEach, for loop, while loop etcand push the values in a new object.
Also make sure that your array syntax is correct because the way you have mentioned it in the question is incorrect.
const data = [{ key:"name", value: "John" },{ key:"age", value:25 },{ key:"job", value:"software engineer" } ];
const res = {};
data.forEach(item => { res[item.key] = item.value});
console.log(res);
I am new to JS and I am trying to do a basic operation on a JS object.
I have the following object:
var originalObj = {
id: 1,
name: 'originalObj'
}
Now I would like to add another object as a field to originalObj.
var newObj = {
newId: 2,
name: 'newObj'
}
So expected outcome is:
orginalObj = {
id: 1,
name: 'originalObj',
newObj: {
newId: 2,
name: 'newObj'
}
}
What I tried so far:
originalObj.newObj = newObj and originalObj['newObj'] = newObj
This results in:
orginalObj = {
id: 1,
name: 'originalObj',
newObj:
}
Object.assign(originalObj, newObj)
This add all the fields of newObj on the same level as originalObj. Like below:
originalObj = {
id: 1,
name: 'originalObj',
newId: 2,
name: 'newObj'
}
Depends on if you want a deep copy or just a reference.
originalObj.newObj = newObj; will assign a reference to newObj where as
originalObj.newObj = Object.assign({}, newObj); will create a new one.
Note: if your using ECMAScript 2015 (6th Edition, ECMA-262) you can use the spread operator ...
originalObj.newObj = {...newObj};
Example: https://jsbin.com/yisiyip/edit?js,console
originalObj.newObj=newObj; //this should do the job
const originalObj = {
id: 1,
name: 'originalObj'
}
const newObj = {
newId: 2,
name: 'newObj'
}
originalObj = { ...originalObj, newObj }
what's happening here is you are spreading the values of originalObj into an empty object together with the value of newObj by shorthand method
reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
This question already has answers here:
Convert object array to hash map, indexed by an attribute value of the Object
(21 answers)
Closed 4 years ago.
I have a JSON in the format.
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
I want to transform it in an object of the format:
myObj = {NY:"good",FL:"bad",CA:"decent"}
The reason I want this is so that I can easily grab the myObj.NY value.
Short and simple
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
var obj = {};
input.forEach(function(k) {
obj[k.state] = k.status;
});
console.log(obj);
You can try using "Object.assign" and "Array.map" as well like below to achieve your desired result
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
let res = Object.assign(...input.map(({ state, status}) => ({ [state]: status })))
console.log(res)
var myobj = {};
Input.forEach(function (i) { myobj[i.status] = i.state;}
You can do a simple forEach() loop on that array with array destructuring to make your code short and simple.
var input = [{
status: "good",
state: "NY"
},
{
status: "bad",
state: "FL"
},
{
status: "decent",
state: "CA"
}
];
var res = {};
input.forEach(({state, status})=> res[state] = status);
console.log(res);
Using Array.prototype.reduce()
var myObj = input.reduce( (r,x) => { r[x.status] = x.state ; return r }, {})
This can be accomplished as well using map, by assigning the object key through the [key] syntax:
var input = [
{status:"good", state: "NY"},
{status:"bad", state: "FL"},
{status:"decent", state: "CA"}
]
var myObj = Object.assign({}, ...input.map(item => ({
[item.state]: item.status
})));
console.log(myObj);
see https://jsfiddle.net/gL6bcqm1/1/
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Accessing properties of an array of objects
Given:
[{
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}]
What's the best way to get:
['john', 'jane', ...... 'zack']
Must I loop through and push item.name to another array, or is there a simple function to do it?
If your array of objects is items, you can do:
var items = [{
id: 1,
name: 'john'
}, {
id: 2,
name: 'jane'
}, {
id: 2000,
name: 'zack'
}];
var names = items.map(function(item) {
return item['name'];
});
console.log(names);
console.log(items);
Documentation: map()
Use the map() function native on JavaScript arrays:
var yourArray = [ {
'id':1,
'name':'john'
},{
'id':2,
'name':'jane'
}........,{
'id':2000,
'name':'zack'
}];
var newArray = yourArray.map( function( el ){
return el.name;
});
You can do this to only monitor own properties of the object:
var arr = [];
for (var key in p) {
if (p.hasOwnProperty(key)) {
arr.push(p[key]);
}
}
You can use this function:
function createStringArray(arr, prop) {
var result = [];
for (var i = 0; i < arr.length; i += 1) {
result.push(arr[i][prop]);
}
return result;
}
Just pass the array of objects and the property you need.
The script above will work even in old EcmaScript implementations.