[英]Given a function that returns me “[prop1][prop2][prop3]” for a nested javascript object, how do I get the value of object[prop1][prop2][prop3]? [duplicate]
This question already has an answer here: 这个问题已经在这里有了答案:
I am writing a function to convert array to List using Javascript. 我正在编写一个使用Javascript将数组转换为List的函数。
If the input array is as below: 如果输入数组如下:
let inputArray = [1,2,3]
The output object should be like the below: 输出对象应如下所示:
let outputList = {
value: 1,
rest: {
value: 2,
rest: {
value : 3,
rest: null } } }
I have the below function that accepts a nested object as its parameter and returns a string that represents where in the object, the property is null: 我有以下函数,该函数接受嵌套对象作为其参数并返回一个字符串,该字符串表示对象中属性为null的位置:
function getLastValue(object) {
let s = '';
if (object.rest) {
return s += '[rest]' + getLastValue(object.rest);
} else {
return s;
}
And the below function that converts an array to a list: 下面的函数将数组转换为列表:
var list = {value: '', rest: null};
function constructList(arr) {
for (let prop of arr) {
let lastValue = getLastValue(list);
`${list}${lastValue}`.value = prop;
`${list}${lastValue}`.rest = null;
}
return list;
}
The constructList function fails to work as ${list}${lastValue}
is a string. 由于
${list}${lastValue}
是字符串, constructList函数无法工作。 I need to convert the above from 我需要从上面转换
'list[rest][rest]'
to 至
list[rest][rest]
Any help is appreciated! 任何帮助表示赞赏!
This would be a great place to use reduceRight
- construct the innermost object first, and have it be the new value of the accumulator, which is assigned to the next innermost object's rest
property, and so on: 这是使用
reduceRight
的好地方-首先构造最里面的对象,并使其成为累加器的新值,该值将分配给下一个最里面的对象的rest
属性,依此类推:
const constructList = arr => arr.reduceRight( (rest, value) => ({ value, rest }), null ); console.log( constructList([1, 2, 3]) );
To fix your original code, rather than constructing a string that attempts to refer to the nested object, iterate through the nested structure to find the innermost rest
property instead, and return the object that doesn't contain a truthy rest
property: 要修复您的原始代码,而不是构造一个试图引用嵌套对象的字符串 ,而是遍历嵌套结构以查找最里面的
rest
属性,然后返回不包含真实的rest
属性的对象:
function getLastValue(obj) { while (true) { if (!obj.rest) return obj; obj = obj.rest; } } var list = { value: '', rest: null }; function constructList(arr) { for (let prop of arr) { const nestedObj = getLastValue(list); nestedObj.value = prop; nestedObj.rest = {}; } getLastValue(list).rest = null; return list; } console.log( constructList([1, 2, 3]) );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.