3

Let us suppose I have the following object:

{
    foo: "bar"
}

How do I, using javascript, make it:

{
    foo: "bar",
    bar: "foo"
}
trincot
  • 317,000
  • 35
  • 244
  • 286
Wilm hill
  • 63
  • 1
  • 6
  • 1
    `const obj = { foo: "bar" }; obj.bar = "foo";` Read about dot notation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors#Dot_notation – Nick Parsons Feb 17 '19 at 10:57
  • https://stackoverflow.com/questions/736590/add-new-attribute-element-to-json-object-using-javascript – Rashomon Feb 17 '19 at 12:15
  • 2
    There is no such thing as "JSON object". [JSON](https://json.org) is a text representation of some data structure (usually an object or an array). It needs to be parsed in order to re-create data structures similar to those used to create it. There is no JSON in your question, only a Javascript object. Read about [objects in Javascript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects). – axiac Feb 17 '19 at 12:16
  • When I use this method, I get an error that the element is not defined. – Wilm hill Feb 17 '19 at 14:49

2 Answers2

3

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.

jo_va
  • 13,504
  • 3
  • 23
  • 47
0

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)
brk
  • 48,835
  • 10
  • 56
  • 78