How overwrite and combine two objects in js? - javascript

I have two objects.
ObjectA = {name: 'Peter', age: 56, country: 'USA'}
ObjectB = {age: 34}
I want to update ObjectA to become
{name: 'Peter', age: 34, country: 'USA'}
if (ObjectB) {
const newObject = ObjectA[Object.keys(ObjectB)[0]] === ....
}
What would be a better way to update ObjectA?

ES9/Regular Javascript
let object1 = {
foo: 'foo'
}
let object2 = {
bar: 'bar'
}
console.log({ ...object1, ...object2 })
console.log(Object.assign(object1, object2))

Just use Object.assign(ObjectA, ObjectB)

Related

How do I convert an array of objects into an object (dynamically) in JavaScript [duplicate]

This question already has answers here:
Convert array of objects with same property to one object with array values
(6 answers)
Closed 2 months ago.
I have an array of objects that looks like this:
arr = [
{name: "john", age: 23},
{name: "mary", age: 40},
{name: "zack", age: 17}
]
I am trying to convert it into something like this:
{
name: ["john", "mary", "zack"],
age: ['23', 40, 17]
}
i have tried the following
arr.map(item => item.name)
arr.map(item => item.age)
return {names, ages}
and it works fine but this assumes that you already know, beforehand, the keys of the objects you're converting.
I want to be able to load the object keys and corresponding array of values dynamically. Assuming i don't know that the objects in our example array have "name" and "age" as keys.
You could reduce the array and the entries of the object and collect the values in the group of the keys.
const
data = [{ name: "john", age: 23 }, { name: "mary", age: 40 }, { name: "zack", age: 17 }],
result = data.reduce((r, o) => Object.entries(o).reduce((t, [k, v]) => {
if (!t[k]) t[k] = [];
t[k].push(v);
return t;
}, r), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could get the key of the first element and then map through it. With each, get its corresponded values
const arr = [
{ name: "john", age: 23, gender: "male" },
{ name: "mary", age: 40, gender: "female" },
{ name: "zack", age: 17, gender: "male" },
]
const res = Object.keys(arr[0]).reduce((acc, el) => {
const values = arr.map((item) => item[el])
return { ...acc, [el]: values }
}, {})
console.log(res)
Assuming that each object in your list has the same keys you could get the keys of the first object
const keys = Object.keys(arr[0])
and then map through the keys with your above approach
const returnObj = {}
keys.forEach(key => {
returnObj[key] = arr.map(item => item[key])
})
return returnObj
You can use Object.entries for the mapping.
var arr = [
{name: "john", age: 23},
{name: "mary", age: 40},
{name: "zack", age: 17}
];
var entries = arr.map((item) => Object.entries(item));
var result = {};
entries.forEach(entry => {
entry.forEach(item => {
if (result[item[0]] && result[item[0]].length > 0) {
result[item[0]].push(item[1]);
} else {
result[item[0]] = [item[1]];
}
});
});
console.log(result);
You can make use of Array.reduce and Object.keys.
let arr = [
{name: "john", age: 23},
{name: "mary", age: 40},
{name: "zack", age: 17}
]
const formatData = (data) => {
return data.reduce((res, obj) => {
Object.keys(obj).map(d => {
res[d] = [...(res[d] ||[]), obj[d]]
})
return res;
}, {})
}
console.log(formatData(arr))
You can do this with Ramda
import { mergeWith, concat } from “Ramda”
const mergeConcat = mergeWith(concat)
mergeConcat(arr)

How to map an Object's property to another object?

I have two objects:
objectA = {
name: 'myname',
surname: 'mysurname',
age: 'myage'
}
objectB = {
birthdate: 'mybirthdate',
school: 'myschool'
}
How can I add objectA's age property to objectB to get the result below:
objectB = {
birthdate: 'mybirthdate',
school: 'myschool',
age: 'myage'
}
There are various ways :
easiest one :
let obj1 = { food: 'pizza', car: 'ford' }
let obj2 = { animal: 'dog' }
Object.assign(obj1, obj2); //es6
console.log(obj1);
Try using either:
objectB.age = objectA.age
or
Object.assign(objectB, { age: objectA.age} );
If you want the object to be a new object (instead of modifying objectB), you can use object rest spread:
objectA = {
name: 'myname',
surname: 'mysurname',
age: 'myage'
}
objectB = {
birthdate: 'mybirthdate',
school: 'myschool'
}
objectC = { ...objectB, age: objectA.age }
console.log(objectC)

Ramdajs: How to filter a list based on a object property?

const abby = {name: 'Abby', attributes: {age: 7, hair: 'blond'}};
const fred = {name: 'Fred', attributes: {age: 12, hair: 'brown'}};
const rusty = {name: 'Rusty', attributes: {age: 10, hair: 'brown'}};
const alois = {name: 'Alois', attributes: {age: 15, disposition: 'surly'}};
const kids = [abby, fred, rusty, alois];
console.log = function(text) {
$('#console').append($('<div>').text(text));
};
// current code
console.log(R.filter(R.compose(R.propEq('hair', 'blond'), R.props('attributes')))(kids));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<div id="console"></div>
I want to get the objects whose hair is 'blond'. I tried using compose but unluckily it doesn't work. I am still new with ramda.
Your initial attempt is almost correct; R.props('attributes') should have been R.prop('attributes') instead:
R.filter(R.compose(R.propEq('hair', 'blond'), R.prop('attributes')))(kids)
However you may find it easier to use pathSatisfies if you need to assert against a nested property:
Returns true if the specified object property at given path satisfies the given predicate; false otherwise.
const {filter, pathSatisfies, equals} = R;
const abby = {name: 'Abby', attributes: {age: 7, hair: 'blond'}};
const fred = {name: 'Fred', attributes: {age: 12, hair: 'brown'}};
const rusty = {name: 'Rusty', attributes: {age: 10, hair: 'brown'}};
const alois = {name: 'Alois', attributes: {age: 15, disposition: 'surly'}};
const kids = [abby, fred, rusty, alois];
console.log(
filter(pathSatisfies(equals('blond'), ['attributes', 'hair']), kids)
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
References
props
prop
pathSatisfies
it is year 2020, I guess use pathEQ is much simple
const R = require("ramda");
let out = "";
const abby = { name: "Abby", attributes: { age: 7, hair: "blond" } };
const fred = { name: "Fred", attributes: { age: 12, hair: "brown" } };
const rusty = { name: "Rusty", attributes: { age: 10, hair: "brown" } };
const alois = { name: "Alois", attributes: { age: 15, disposition: "surly" } };
const kids = [abby, fred, rusty, alois];
out = R.filter(R.pathEq(["attributes", "hair"], "blond"))(kids);

Can we add properties to immutable object in JavaScript?

An object is like:
const obj = [{name: 'Alex', age: 20}, {name: 'James', age: 22}];
This obect is immutable from Immutable.js.
Is it possible to add a new key for each object? example:
const obj = [{name: 'Alex', age: 20, city: 'New York'}, {name: 'James', age: 20, city: 'Rome'}];
Not if it’s immutable. But that is ok, you can copy all the properties over to a new structure and add whatever you need to that way:
const newData = obj.map(person => ({
...person,
city: someLogicToDetermineCity(person)
}))
function someLogicToDetermineCity(person) {
// logic based on person
return city
}
const doesn't create immutability - it just means that the reference assigned to it on creation cannot be changed later (which simply means that you cannot assign a new value to it).
See these examples:
const a = {}
a = { name: "peter" } // => TypeError: invalid assignment to const `a'
However it's no problem to assign a property on a:
const a = {}
a.name = "peter"
console.log(a); // => { "name": "peter" }
The same applies for Array objects:
const arr = [{}]
arr.push(1);
arr[0].name="peter"
console.log(arr);
// [
// {
// "name": "peter"
// },
// 1
// ]

how to destruct part of properties from an object

For example, I got an object like this:
obj1 = {
name: 'Bob',
age: 20,
career: 'teacher'
}
Now I need to duplicate part of its properties instead all of them.
obj2 = {
name: '',
age: '',
}
I know I can do it like obj2.name = obj1.name, which will be verbose if many properties need to be duplicated. Are there any other quick ways to solve this problem?
I tried
let {name: obj2.name, age: obj2.age} = obj1;
but got error.
Actually you don't need object destructuring, just simple assignment:
obj2 = { name: obj1.name, age: obj1.age }
Now, obj2 holds wanted properties:
console.log(obj2);
// Prints {name: "Bob", age: 20}
If you want to merge old properties of obj2 with new ones, you could do:
obj2 = { ...obj2, name: obj1.name, age: obj1.age }
Drop the let (you're not declaring variables) and surround with parentheses:
({name: obj2.name, age: obj2.age} = obj1);
I guess you can use ES6 Object destructuring syntax
var obj = { name: 'kailash', age: 25, des: 'backenddev'}
({name} = obj);
You could use the target object as template for the properties and assign the values of obj1 with a default value of the target object.
var obj1 = { name: 'Bob', age: 20, career: 'teacher' },
obj2 = { name: '', age: '' };
Object.keys(obj2).forEach(k => obj2[k] = obj1[k] || obj2[k]);
console.log(obj2);
Another solution would be to write a reuable method for this. You can supply an object and the methods you would like to copy.
const duplicatePropertiesFromObject = (obj, propertyNames = [], newObj = {}) => {
Object.keys(obj).forEach((key) => {
if (propertyNames.includes(key)) {
newObj[key] = obj[key];
}
});
return newObj;
}

Categories

Resources