在 Javascript 中构建嵌套对象 [英] Build Nested Object in Javascript
本文介绍了在 Javascript 中构建嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图构建一个嵌套对象,我会尽量让自己清楚.
我有这个 json 结构:
<代码> {"origin.geo.country": "美国","origin.geo.state": "纽约",origin.geo.zip":4444,"user.name": "迈克尔","user.surname": "约旦"}
我需要一个输出如下内容的函数:
<预><代码>{起源: {地理:{国家:美国",状态:纽约",邮编:4444}},用户:{姓名:迈克尔",姓氏:乔丹"}}我知道我必须使用递归来实现这一点,但我无法对其进行编码.你们能帮我解决这个问题吗?
谢谢.
解决方案
各位,
@Ben Beck 的回答帮助了我.
我只需要对函数做一些小改动:
function (path,value,obj) {var parts = path.split("."), part;//引用父对象var 父 = obj;while(part = part.shift()) {//这里我检查属性是否已经存在if(!obj.hasOwnProperty(part)) obj[part] = {};//如果是我设置 prop 值的最后一个索引if(parts.length === 0) obj[part] = value;obj = obj[部分];//更新指针"}//最终返回填充的对象返回父母;}
I trying to build a nested object, I'll try to make myself clear.
I have this json structure:
{
"origin.geo.country": "USA",
"origin.geo.state": "NY",
"origin.geo.zip": 4444,
"user.name": "Michael",
"user.surname": "Jordan"
}
And I need a function that outputs something like this:
{
origin: {
geo: {
country: "USA",
state: "NY",
zip: 4444
}
},
user: {
name: "Michael",
surname: "Jordan"
}
}
I know i have to use recursion to achieve this, but I'm not able to code it. Can you guys help me with this?
Thanks.
解决方案
So guys,
@Ben Beck answer helped me.
I just need to make some minor changes to the function:
function (path,value,obj) {
var parts = path.split("."), part;
//reference the parent object
var parent = obj;
while(part = parts.shift()) {
// here I check if the property already exists
if( !obj.hasOwnProperty(part) ) obj[part] = {};
// if is the last index i set the prop value
if(parts.length === 0) obj[part] = value;
obj = obj[part]; // update "pointer"
}
//finally return the populated object
return parent;
}
这篇关于在 Javascript 中构建嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文