[英]How to get the first unique item of a deep-nested object in an array in Javascript
[英]How can I get some value of a deep-nested object?
我必須動態構建兩種類型的數組。
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']
有時,或多或少有一個像“標題”這樣的級別。 如果我想調用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": "<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'))
它可與以下其他解決方法一起使用:
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", "<p>description text</p>"); console.log(myObject); setValueByKeypath(myObject, "fields>title", "Headline"); console.log(myObject); setValueByKeypath(myObject, "meta>id", "995915463198380032"); console.log(myObject);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.