简体   繁体   English

通过键获取对象,并保留它的键

[英]get object by key, keep key with it

I am filtering data that looks like below with json[username] for example.例如,我正在使用json[username]过滤如下所示的数据。

data looks like:数据看起来像:

{"albert":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"sally":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"petey":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}
{"gilbert":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}

so, for instance json[sally] brings in sally data but omits her name (the key) giving me the below:因此,例如json[sally]引入了sally数据,但省略了她的名字(密钥),给出了以下内容:

{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}

I need to bring in/keep the name key as well.我还需要带入/保留姓名密钥。 ie the whole line:即整行:

{"sally":{"userCData":[{"id":"slz1","checked":"false"},{"id":"slz2",...................]}}

If I hardcode it: user = "{" + username + ":"+json[username]+"}";如果我硬编码它: user = "{" + username + ":"+json[username]+"}"; the object stops working: consoles as just {sally:[object Object]} .对象停止工作:控制台只是{sally:[object Object]} Anyway to achieve this?无论如何要实现这一目标?

You can loop over the json and try it in this way,你可以循环遍历json并用这种方式尝试一下,

for(let item in json){
    let data = {};
    data[item] = json[item];
    console.log(data);
}

You can simply loop over the data like so:您可以像这样简单地循环数据:

for(var key in data){
    console.log(key);
    console.log(data[key]);
}

here, key will store the name sally, while data stored in sally is extracted via data[key].在这里,key 将存储名称 sally,而存储在 sally 中的数据是通过 data[key] 提取的。

You can also refer this post: How to loop through key/value object in Javascript?您还可以参考这篇文章: How to loop through key/value object in Javascript?

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

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