Let us suppose I have the following object:
{
foo: "bar"
}
How do I, using javascript, make it:
{
foo: "bar",
bar: "foo"
}
Let us suppose I have the following object:
{
foo: "bar"
}
How do I, using javascript, make it:
{
foo: "bar",
bar: "foo"
}
You simply need to assign it a new property using dot notation:
const data = {
foo: "bar"
};
data.bar = 'foo';
console.log(data);
If your property names are variables, use bracket notation instead:
const data = {
foo: "bar"
};
const newProp = 'bar';
data[newProp] = 'foo';
console.log(data);
See the doc on property accessors here.
Seems you want to create new key by reversing the actual key and value. In that case use Object.keys
which will give an array and create new keys based on that
let data = {
foo: "bar"
}
Object.keys(data).forEach((item) => {
data[data[item]] = item
});
console.log(data)