简体   繁体   English

如何向对象添加更多信息?

[英]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:我如何使用 javascript制作它:

{
    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在这种情况下,使用Object.keys它将给出一个数组并基于该数组创建新的键

 let data = { foo: "bar" } Object.keys(data).forEach((item) => { data[data[item]] = item }); console.log(data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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