简体   繁体   中英

How do I add more information to an object?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM