const a = {
b: {
c: 'Hi!'
}
};
const { b: { c } } = a;
Is it possible rename b in this case? I want get c and also rename b.
You could destructure with a renaming and take the same property for destructuring.
const a = { b: { c: 'Hi!' } };
const { b: formerB, b: { c } } = a;
console.log(formerB)
console.log(c);
You can destructure the same property multiple times, onto different targets:
const { b: {c}, b: d } = a;
This assigns a.b.c to c and a.b to d.
Related
This question already has an answer here:
object destructuring: how to use intermediate nested property
(1 answer)
Closed 12 days ago.
if I have the following object:
const obj = {
a: {
b: 'val',
},
};
and I want to destructure both a and b from the object, how would I go about doing it? I know this:
const { a: { b } } = obj;
but this doesn't let me access a. How can I also make a accessible in the code?
Just include it.
const obj = {
a: {
b: 'val',
},
};
const { a, a: { b } } = obj;
console.log(a);
console.log(b);
I am trying to change only the value of copied object, not the main but both objects change as of the result of running this code.
const Randomdata = {
a: 10,
b: 5,
c: {
f: "value1",
q: "value2"
}
};
function copy(MainObj) {
let ObjCopy = {};
for (let key in MainObj) {
ObjCopy[key] = MainObj[key];
}
return ObjCopy;
}
const newObj = copy(Randomdata);
Randomdata.c.q = "value3";
console.log(newObj);
console.log(Randomdata);
Though JSON.parse and JSON.stringify will work , but you will need a recusive function if want to achieve the same result using for..in. The reason is value of key c is a object and when you are copying it, it is just referencing to the old copy
const Randomdata = {
a: 10,
b: 5,
c: {
f: "value1",
q: "value2"
}
};
function copy(MainObj, ObjCopy) {
for (let key in MainObj) {
// check if the value is a object , if so then
// reclusively call the same function
if (typeof MainObj[key] === 'object') {
copy(MainObj[key], ObjCopy)
} else {
ObjCopy[key] = MainObj[key];
}
}
return ObjCopy;
}
const newObj = copy(Randomdata, {});
Randomdata.c.q = "value3";
console.log(newObj);
console.log(Randomdata);
I am looking for the most concise way to have a new object out of the fields of the deconstructed one.
let obj = {
a: 1,
b: 2,
c: null
}
Currently I have:
let {a, c} = obj;
let data = {a, c}
What I wished I would be having:
let data = {a, c} = obj;
// but data actually becomes {a, b, c}
// and not {a, b} as I wished it to be.
Although your code looks fine may be if your task consists in cherrypicking keys and put it in another object destructuring is not the best approach:
const object = { a: 5, b: 6, c: 7 };
const picked = (({ a, c }) => ({ a, c }))(object);
console.log(picked)
You can define a function that will provide the destructured object as the return value, and assign the call to data:
const obj = {
a: 1,
b: 2,
c: null
}
const partial = ({ a, c }) => ({ a, c })
const data = partial(obj)
console.log(data)
Unfortunately this isn't possible in one line without some setup, but the setup is worthwhile if you are creating the same partial object a lot of places in your source.
Rather than rely on destructuring for this, you can implement a version of the commonly found "pick" function, that accepts as input an object and an array of keys to pull out of that object:
function pick(obj, keys) {
return keys.reduce((memo, key) => {
memo[key] = obj[key];
return memo;
}, {});
}
const obj = { a: 1, b: 2, c: 3 }
const data = pick(obj, ['a', 'b']);
console.log(data); // { a: 1, b: 2}
Normally I would consider performance less important than readability, which is highly subjective. But in this case, both the pick solution above and the one-liners are orders of magnitude slower than your original two-liner, though pick wins out over the one-liner by a comparatively small margin: https://jsperf.com/testaagwt14124oih1oij
Consider a function returns an nested object and I want to modify the property inside the nested object.
In the below example, I'm calling the function many times or I need to store it in a temporary variable. Is there a way to invoke only once inside the braces and spread/modify inside the same object many times.
const getObject = () => {
return {
a: {
b: {
c: 1,
d: 2,
}
},
e: 3
}
}
var modifiedD = {
...getObject(),
a: {
b: {
...getObject().a.b,
d: 4
}
}
}
console.log(modifiedD);
when declaring a key after ...getObject() it replace the whole value. It does not merge the inner object behind a.
So you could do it as you have done and call getObject() multiple time.
An other solution could be to handle it using a function of your own merging the objects, like :
function mergeObjects(obj1, obj2) {
// We are going to copy the value of each obj2 key into obj1
Object.keys(obj2).forEach((x) => {
// If we have an object, we go deeper
if (typeof obj2[x] === 'object') {
if (obj1[x] === void 0) {
obj1[x] = {};
}
mergeObjects(obj1[x], obj2[x]);
} else {
obj1[x] = obj2[x];
}
});
return obj1;
}
const getObject = () => {
return {
a: {
b: {
c: 1,
d: 2,
}
},
e: 3
}
}
const modifiedD = mergeObjects(getObject(), {
a: {
b: {
d: 4,
},
},
});
console.log(modifiedD);
WARNING, the function I have made mutate the object which may not be the best answer
Or call it only once and then set the keys one by one like :
const getObject = () => {
return {
a: {
b: {
c: 1,
d: 2,
}
},
e: 3
}
}
const modifiedD = getObject();
modifiedD.a.b.d = 4;
console.log(modifiedD);
Further to my previous answer, as Grégory NEUT pointed out you could have a lot larger complexity.
If so, you could simply create two objects and then merge them. I found a function code snippet to be able to do that using Object.assign
Example:
const getObject = () => {
return {
a: {
b: {
c: 1,
d: 2,
}
},
e: 3
}
}
var modifiedD = getObject();
var newD = {
a: {
b: {
d: 4
},
y: 1
},
z: 20
}
/** TAKEN FROM https://gist.github.com/ahtcx/0cd94e62691f539160b32ecda18af3d6 **/
// Merge a `source` object to a `target` recursively
const merge = (target, source) => {
// Iterate through `source` properties and if an `Object` set property to merge of `target` and `source` properties
for (let key of Object.keys(source)) {
if (source[key] instanceof Object) Object.assign(source[key], merge(target[key], source[key]))
}
// Join `target` and modified `source`
Object.assign(target || {}, source)
return target
}
modifiedD = merge(modifiedD, newD);
console.log(modifiedD);
You can try the following:
getParentObj(path, obj) {
return path.split('.').reduce((o,i)=>o[i], obj);
}
const parent = getParentObj('a.b', getObject());
parent[d] = 24;
how to compare two objects for equality if they have functions? lodash's isEqual works really well until functions are thrown in:
_.isEqual({
a: 1,
b: 2
}, {
b: 2,
a: 1
});
// -> true
_.isEqual({
a: 1,
b: 2,
c: function () {
return 1;
}
}, {
a: 1,
b: 2,
c: function () {
return 1;
}
});
// -> false
This is what I tried:
_.isEqual(o1, o2, function(val1, val2) {
if(_.isFunction(val1) && _.isFunction(val2)) {
return val1.toString() === val2.toString();
}
})
Lodash supports a customizer function which allows you to write your own equality checks. This seems to be a good enough test to see if the functions are character by character the same.
Are you sure you want to compare functions? If you only care about comparing every property that isn't a function, this is easy to do with lodash:
var o1 = { a: 1, b: 2, c: function() { return 1; } },
o2 = { a: 1, b: 2, c: function() { return 1; } };
_.isEqual(o1, o2)
// → false
_.isEqual(_.omit(o1, _.functions(o1)), _.omit(o2, _.functions(o2)));
// → true
The functions() function returns a list of function properties, and using omit(), you can get rid of them.
Try isEqualWith instead:
import { isEqualWith, isFunction } from 'lodash-es'
const o1 = { fn() {} }
const o2 = { fn() {} }
const equal = isEqualWith(o1, o2, (v1, v2) =>
// if `customizer` returns `undefined`, comparisons are handled by the method instead
isFunction(v1) && isFunction(v2) ? `${v1}` === `${v2}` : undefined,
)
console.log({ equal }) // { equal: true }
As the lodash documentation states:
Functions and DOM nodes are not supported.
https://lodash.com/docs#isEqual