![](/img/trans.png)
[英]Array of objects: accessing an object's value without iterating through the array
[英]Can I build a string from an array with a value in between without iterating through the array twice?
我有两个变量name
和values
,其中 name 是一个简单的字符串Bob
, values 是一个字符串数组。
根据values
的长度,我想构建一个字符串,它由每个值和一个左花括号组成。 但是每个左大括号都需要一个相应的右大括号。
假设我有以下值: ["a", "b", "c"]
,我的字符串应该如下所示:
a: { b: { c: { Bob } } }
那么在模板文字中可以做什么:
${values.map(v => ` ${v}: { `).join("")} ${name} ${values.map(() => `}`).join("")}
除了右括号两次超过values
之外,还有另一种方法吗? 我的头被卡住了。
这应该可以做到(尽管我不太确定您想用它做什么,请参阅@Seblor 的评论):
const nam="Bob", arr=["a","b","c"]; const res=[...arr,nam].join(": { ")+" }".repeat(arr.length) console.log(res);
const values = ['a', 'b', 'c'] const result = values.reduceRight((string, prop) => `${prop}: {${string}}`, 'bob') console.log(result)
这可能不适合您的特定任务,但您可以通过从内到外运行 reduce 来构建这样一个 object:
const path = ["a", "b", "c"]; const name = "bob"; const result = path.reduceRight((acc, v) => ({[v]: acc }), { name }); console.log(JSON.stringify(result));
不那么花哨,但严格避免扫描字符串两次。
function addKey(keyArray, value) { if (keyArray.length === 0) return value; const key = keyArray.pop(); return addKey(keyArray, { [key]: value }); } const result = addKey(['a', 'b', 'c'], 'hello'); console.log(result);
诀窍是向后工作,这样您就不必反转数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.