如何使用javascript向json对象添加父键 [英] how do i add a parent key to json object using javascript

查看:103
本文介绍了如何使用javascript向json对象添加父键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用javascript向整个JSON对象添加包装密钥并遇到一些问题。例如:

I'm trying to add a wrapping key to an entire JSON object with javascript and having some issues. For example:

var obj = { "name" : "Bob", "city" : "Detroit", "state" : "MI" };

我想为此添加父键,以便最终输出为:

I want to add a parent key to this so it would eventually output as:

{ "personalization" : { "name" : "Bob", "city" : "Detroit", "state" : "MI" } }

由于var obj是动态构建的,我想做这样的事情,但它不喜欢在那里有一个var:

Since the var obj is dynamically built I thought of doing something like this, but it doesn't like having a var in there:

var obj = { "name" : "Bob", "city" : "Detroit", "state" : "MI" };
var obj2 = { "personalization" : obj };


推荐答案

这是评论,但评论不能有Stack Snippets,所以它是CW。

This is a comment, but comments can't have Stack Snippets, so it's a CW.

你最后的例子很好,那里没问题。这正是你如何获取一个对象并使它成为你通过对象初始化器创建的另一个对象的属性:

Your example at the end is just fine, there's no problem there. That's exactly how you'd take an object and make it a property of another object you're creating via an object initializer:

var obj = { "name" : "Bob", "city" : "Detroit", "state" : "MI" };
var obj2 = { "personalization" : obj };
snippet.log(obj2.personalization.name); // Shows Bob

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

这篇关于如何使用javascript向json对象添加父键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆