Trying to get better with data mutating in vanilla JS and have not been successful here.
I am just trying to use the values of one object to create keys for another format.
Also tried things like string interpolation ${}
etc, can someone please show my error? The example in comment is what I'm after so like
var = { x: 'left', y: 'top', z: 'front' }
=> becomes => {left: top, extra: { front: true }
but obviously struggling with syntax, thank you!
const obj1 = {
aKey: 'a_value',
bKey: 'b_value',
cKey: 'c_value'
}
/************************* pseudo what I want to turn this into:
obj2 = {
[a_value]: [b_value],
adhocKey: {
[c_value]: true
}
}
*/
const obj2 = {
obj1[aKey]: obj1[bKey],
adhocKey: {
obj1[cKey]: true
}
}
console.log(obj1)
const obj3 = {
obj1.aKey: obj1.bKey,
adhocKey: {
obj1.cKey]: true
}
}
console.log(obj2)
See description details
You can use the value of x
(or z
) as a key by using the bracket-notation e.g. [x]: ...
To get the value of y
, you should use the dot-notation.
const
original = { x: 'left', y: 'top', z: 'front' },
result = { [original.x]: original.y, extra: { [original.z]: true } };
console.log(result); // { left: top, extra: { front: true }