Adding or appending object with object javascript - javascript

i am having 2 objects and the code is
Object 1
var existingValue=self.get('objHubDto').ftd.gridDataDTO.gridDTOMap[name].gridDataMap;
Object 2
var newValue = self.get('childDataList')
I need to merge/add/append this two in newvalue value eventhough it having duplicate key values

Following is a very basic example to merge by keeping both values, however, you can create new object rather mutating existing one.
let obj1 = { a: 1, b: 2, c: 3 };
let obj2 = { a: 9, d: 8, e: 7 };
Object.entries(obj2).forEach(([key, val]) => {
obj1[key] = obj1[key] ? [obj1[key], val] : val;
});
console.log(obj1);

Related

JS: How to insert object into array alphabetically by key? [duplicate]

This question already has answers here:
How can we custom sort JavaScript object keys?
(3 answers)
Closed 24 days ago.
I have the following Javascript object:
let obj = {
a: 1,
b: 2,
d: 4
}
obj["c"] = 3
When I log this, the keys are in the order a, b, d, c. Is there a way to make it so that c is inserted between b and d?
One method is to create a new object with Object.fromEntries after sorting the entries of the original object.
let obj = {
a: 1,
b: 2,
d: 4
}
obj["c"] = 3;
let newObj = Object.fromEntries(Object.entries(obj).sort());
console.log(newObj);
Alternatively, just sort the keys before looping over them.
let obj = {
a: 1,
b: 2,
d: 4
}
obj["c"] = 3;
for (const key of Object.keys(obj).sort()) {
console.log(key, '=', obj[key]);
}

In Javascript, given key/value pairs, return values from array of keys

const pairs = { a : 1, b : 2, c : 3 }
const keyArray = [a, b, c]
I'm trying to get a function or w/e that returns [1, 2, 3]. can't think of anything please help
In javascript all keys of an object are actually strings, and can be addressed using the same strings.
Your code is creating an array containing the values of the - possibly uninitialized - variables a, b and c, which then produces [undefined, undefined, undefined], or else whatever those variables contain.
You need to make keyArray contain strings instead, and then you can use the map() function to produce the desired result:
const pairs = { "a" : 1, "b" : 2, "c": 3 }
const keyArray = ["a", "b", "c"]
const values = keyArray.map(key => pairs[key]);
console.log(values);
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
const keyArray = ['a', 'b', 'c']
for(const item of keyArray)
{
console.log(pairs[item])
}
You need to make your items inside the array and object as strings
Well since it's Javascript
Object.values() should do it.
const keyArray = Object.values(pairs)
const pairs = { 'a' : 1, 'b' : 2, 'c': 3 }
for(const [key , value] of Object.entries(pairs))
{
console.log(key) // a , b, c
console.log(value) // 1, 2, 3
}

Loop through object, and return the sum of each value with similar properties

this might be a simple fix... but with the code below, I'm getting {a:2}, when it should just be 1.
const object = {a:1, b:2, b:2};
let sum = {};
for(let property in object){
sum[property] = object[property] + object[property];
}
console.log(sum);
Not sure what the issue is.. Also, I'm trying to understand how the properties are passed into the sum object. Because from my understanding sum[property] returns a value, not a property; and so does object[property]. So how do a: and b: properties get passed into sum? Trying to get a visualization of how this works.
Thank you
First:
This line:
sum[property] = object[property] + object[property];
will sum two a properties
sum["a"] = object["a"] + object["a"]
That causes sum["a"] === 2
Second:
Object can not have the same properties.
Alternative:
You can use array of objects, like this:
const arr = [{a: 1}, {b: 2}, {b: 2}];
And fix the code to return the sum of each value with similar properties
const arr = [{a:1}, {b:2}, {b:2}, {a: 8, b: 5}];
let sum = {};
arr.forEach(object => {
for(let property in object) {
if (sum[property] === undefined) sum[property] = object[property];
else sum[property] += object[property];
}
})
console.log(sum); // { a: 9, b: 9}
const object = {a:1, b:2, b:2};
console.log(object) //{a:1, b:2}
There can only be one unique key

JavaScript/Coffeescript sum objects

I would love to "add/merge" (not sure how to call that) some objects in this manner:
obj1 = {
a: 1,
b: 1,
c: 1
}
obj2 = {
a: 1,
b: 1
}
obj1 + obj2 => { a: 2, b: 2, c: 1 }
Is there any way of achieving this? Tried, Object.assign(obj1, obj2) but It will not add properties like I need it to be done (it returns in { a: 1, b: 1, c: 1})
There isn't a built-in way to do it but you can enumerate the properties of one object and add their values to another.
const a = { a: 1, b: 1, c: 1 };
const b = { a: 1, b: 1 };
for(const prop in b) {
a[prop] = (prop in a ? a[prop] : 0) + b[prop];
}
console.log(a);
The prop in a check is so that we don't end up with NaN by adding undefined to the value in b.
You could use reduce to combine n number of objects like so:
const a = { a: 1, b: 1, c: 1 };
const b = { a: 1, b: 1 };
const c = { a: 1, c: 1 };
const result = [a, b, c].reduce((p, c) => {
for(const prop in c) {
p[prop] = (prop in p ? p[prop] : 0) + c[prop];
}
return p;
}, {});
console.log(result);
You didn't mention how you wanted to deal with properties in the prototype chain. You should know that for...in will enumerate properties in the prototype chain and prop in x will also examine the prototype chain. If your only want to enumerate the objects own properties then you could use Object.entries() to get its own properties or do a hasOwnProperty(...) check within the for...in and in place of the prop in x check. If you don't do any prototypal inheritance with your models then you may not care.
A quick answer:
let sum = {};
let keys = new Set(Object.keys(obj1))
Object.keys(obj2).map(x => keys = keys.add(x))
keys.forEach(x => {
let op1 = obj1[x] || 0;
let op2 = obj2[x] || 0;
sum[x] = op1 + op2;
})
Create an empty object:
var obj3 = {};
Use the spread operator to grab all the keys from both objects, then add them to the new object like so:
for(var i in {...obj1, ...obj2}) {
obj3[i] = (obj1[i] || 0) + (obj2[i] || 0);
}
var obj1 = {
a: 1,
b: 1,
c: 1
}
var obj2 = {
a: 1,
b: 2,
d: 3
}
var obj3 = {};
for(var i in {...obj1, ...obj2}) {
obj3[i] = (obj1[i] || 0) + (obj2[i] || 0);
}
console.log(obj3);

Explanation for in loop JavaScript

Who can explain how this for in loop works and why it's assign keys of object to array
var o = {
a: 1,
b: 2,
c: 3,
d: 4
};
var a = [],
i = 0;
for (a[i++] in o);
console.log(a);
Using a side effect when enumerating the object, and using an empty statement, each key is stored in the array a; first key in a[0], next in a[1] etc.
It is not necessary however since you could just use Object.keys(o)
var o = {
a: 1,
b: 2,
c: 3,
d: 4
};
var a = [],
i = 0;
for (a[i++] in o); // do nothing loop
console.log(a,Object.keys(o));

Categories