我必须动态构建两种类型的数组。
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']
有时候,或多或少都有一个类似于“标题”的等级。
如果我想称呼标题,则数组就像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]];
}
谢谢您的帮助。
答案 0 :(得分:2)
您可以创建一个函数来查找传递的级别。您可以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'))
答案 1 :(得分:0)
它与以下其他解决方法一起工作:
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]];
}
也许您有一个更聪明的解决方案。
答案 2 :(得分:0)
/*
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);