如何获得深层嵌套对象的某些价值? [英] How can I get some value of a deep-nested object?
问题描述
我必须动态构建两种类型的数组.
There are two types of arrays which I have to build dynamically.
data['fields']['title']
和
data['fields']['description']['html']
它返回此结构的内容:
{
"fields": {
"title": "Headline",
"description": {
"html": "<p>description text</p>"
}
},
"meta": {
"id": "995915463198380032"
}
}
问题是动态"的.
我调用一个函数,并像"description>html
"那样给出通过它的路径.
我将字符串分为描述"和"html".
但是,现在我该如何构建数组:data['fields']['description']['html']
I call a function and give the path through it like "description>html
".
I split the string into "description" and "html".
But how do I build now the array: data['fields']['description']['html']
有时候,有些级别或多或少像标题".
如果我想称呼标题,数组就像data['fields']['title']
Sometimes there is a level more or less like "title".
If I want to call title, the array is like data['fields']['title']
所以数组的内容和数量是动态的.
So the content and the number of parts in the array are dynamic.
我自己尝试过这个:
function comfort_x(item_fields) {
var splitter = item_fields.split(">");
var content = new Array();
for (var i = 1; i < splitter.length; ++i) {
content['splitter['+i+']'] = splitter[i];
}
data['fields'][splitter[0]][splitter[1]];
}
谢谢您的帮助.
推荐答案
您可以创建一个函数来查找要传递的级别.您可以通过>
只是split
路径,并使用源输入来缩小该数组.
You can create a function that will look up to the level you are passing. You can just split
your path by >
and reduce that array with the source input.
(data, path) => path.split(">").reduce((r, e) => r[e], data);
这里是一个例子.
var obj = {
"fields": {
"title": "Headline",
"description": {
"html": "<p>description text</p>"
}
},
"meta": {
"id": "995915463198380032"
}
}
var lookUp = (o, path) => path.split(">").reduce((r, e) => r[e], o);
console.log('fields: ', lookUp(obj, 'fields'))
console.log('fields>title: ', lookUp(obj, 'fields>title'))
console.log('fields>description>html: ', lookUp(obj, 'fields>description>html'))
这篇关于如何获得深层嵌套对象的某些价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!