如何获得深层嵌套对象的某些值?
我必须动态构建两种类型的数组。
data['fields']['title']
和
data['fields']['description']['html']
它返回此结构的内容:
{ "fields": { "title": "Headline", "description": { "html": "description text
" } }, "meta": { "id": "995915463198380032" } }
问题是“动态”。
我调用一个函数,并像“ description>html
”一样给出它的路径。 我将字符串拆分为“description”和“html”。 但是我如何构建现在的数组: data['fields']['description']['html']
有时会有一个或多或少像“标题”的水平。 如果我想调用title,数组就像data['fields']['title']
因此,数组中的内容和部件数量是动态的。
我亲自试过这个:
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
路径,并使用源输入减少该数组。
(data, path) => path.split(">").reduce((r, e) => r[e], data);
这是一个例子。
var obj = { "fields": { "title": "Headline", "description": { "html": "description text
" } }, "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'))
它适用于这种附加工作:
switch (splitter.length) { case 0: item.innerHTML = data['fields']; break; case 1: item.innerHTML = data['fields'][splitter[0]]; break; case 2: item.innerHTML = data['fields'][splitter[0]][splitter[1]]; break; case 3: item.innerHTML = data['fields'][splitter[0]][splitter[1]][splitter[2]]; }
也许你有一个更聪明的解决方案。
/* Be careful! The function won't return a new object, but take a reference to the input object aka. alter it and don't deep-clone it. */ const myObject = {}; function setValueByKeypath(object, path, value, separator = ">") { path = path.split(separator); let currentPart = object; for (let i = 0, len = path.length; i < len; i++) { const key = path[i]; const keyValue = (i === len - 1) ? value : {}; if (typeof currentPart[key] === "undefined") { currentPart[key] = keyValue; } currentPart = currentPart[key]; } } setValueByKeypath(myObject, "fields>description>html", "description text
"); console.log(myObject); setValueByKeypath(myObject, "fields>title", "Headline"); console.log(myObject); setValueByKeypath(myObject, "meta>id", "995915463198380032"); console.log(myObject);