Issue
My object
object1 ={
name: xxx,
Id: 212
}
I need a output like:
{
212:xxx
}
Can anyone help me to do it?
for(var key in object1) {
if(object1.hasOwnProperty(key))
{
console.log( eachPeriod[key]);
}
}
Solution
You can set the key
of the object with a variable enclosed with brackets as [Id]
. The convert()
function takes the object as an argument and assigns the value of name
and Id
to the corresponding variables by destructuring. Then, use those variables to construct the object.
const obj = {
name: 'xxx',
Id: 212
};
function convert ({ name, Id }) {
return {
[Id]: name
};
}
console.log(convert(obj));
Answered By – waterloos
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0