Home > Net >  Can I build a string from an array with a value in between without iterating through the array twice
Can I build a string from an array with a value in between without iterating through the array twice

Time:10-07

I have two variables name and values, of which name is a simple string Bob and values is an array of strings.

Depending on the length of values, I would like to build a string, which consists of each value and an opening curly brace. But each opening curly brace needs a respective closing curly brace.

Assuming I have the following values: ["a", "b", "c"], my string should look like:

a: { b: { c: { Bob } } }

So what could be done inside template literal:

${values.map(v => ` ${v}: { `).join("")} ${name} ${values.map(() => `}`).join("")}

Is there another way than over values twice for the closing braces? My head is stuck.

CodePudding user response:

const values = ['a', 'b', 'c']
const result = values.reduceRight((string, prop) => `${prop}: {${string}}`, 'bob')
console.log(result)

CodePudding user response:

This should do it (although I am not quite sure what you want to do with it, see @Seblor's comment):

const nam="Bob", arr=["a","b","c"];

const res=[...arr,nam].join(": { ") " }".repeat(arr.length)

console.log(res);

CodePudding user response:

This may not suit your specific task, but you could build up such an object by running reduce from the inside out:

const path = ["a", "b", "c"];
const name = "bob";

const result = path.reduceRight((acc, v) => ({[v]: acc }), { name });

console.log(JSON.stringify(result));

CodePudding user response:

Less fancy, but strictly avoids scanning the string twice.

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);

The trick is to work backwards so you don't have to reverse the array.

  • Related