NodeJS 使用Array从json循环数据

rbpvctlc  于 2023-11-17  发布在  Node.js
关注(0)|答案(5)|浏览(141)

我试着写一个函数,但我没有实现它。这个函数是这样工作的
输入:changeSetting("a>b>c","hello")
之后,“设置”命名值从{}更改为{"a":{"b":{"c":"hello"}}}
如果输入为changeSetting("a","hello"),json变为{}{"a":"hello"}
我最后一次尝试的代码:

function changeSetting(name,val)  {
  if (name.includes(">")) {
    name = name.split('>')
    let json = {}
    name.map((el,i)=>{
    let last = "" 
    name.filter(el=>!name.slice(i+1).includes(el)).map(el=> {
    if(last!="") {
      json[el] = {}
    }})
    }) 
  }
 }

字符串
我们如何才能做到这一点?(优化不重要,但如果是对我有好处)

fivyi3re

fivyi3re1#

const changeSetting = (setting, target) => {
  if (setting.length < 2) {
    return {
      [setting]: target
    }
  } else {

    const keys = setting.split('>');

    return keys.reduceRight((acc, curr, i) => {

      console.log(acc);

      if(i === keys.length - 1) {
        return acc = {[curr] : target}    
      }
      
        return acc = { [curr]: acc };
    }, {})

    
  }
}

console.log(changeSetting('a', 'hello'));
console.log(changeSetting('a>b>c', 'hello'));

字符串

yws3nbqq

yws3nbqq2#

当你使用字符串时,你可以尝试像这样使用JSON:

function changeSetting(name, val) {
  const keys = name.split(">");
  return JSON.parse(
    [
      "{",
      keys.map((key) => `"${key}"`).join(":{"),
      ":",
      `"${val}"`,
      "}".repeat(keys.length),
    ].join("")
  );
}

字符串

juud5qan

juud5qan3#

有多种方法可以做到这一点,我已经注解了这个片段

const changeSetting = (name, val) => {
    
    // Split and reverse the name letters
    const nameSplit = name.split('>').reverse();

    // Set up the inner most object
    let newObj = {[nameSplit[0]]:val}

    // Now remove the first letter and recurse through the rest
    nameSplit.slice(1).forEach((el, idx) => newObj = {[el]: newObj});

    console.log(newObj);
}

changeSetting("a>b>c", "hello")
changeSetting("a", "hello")
changeSetting("a>b>c>d>e>f>g", "hello")

字符串

wrrgggsh

wrrgggsh4#

你可以通过用String.prototype.split()在所有>上分割name来创建一个数组,然后用Array.prototype.reduceRight()创建一个元素数组,对象初始值为{},并添加键值对,但在最后一个元素上,值应该是变量val
代码:

const changeSetting = (name, val) => name
  .split('>')
  .reduceRight((a, c, i, arr) => ({ 
    [c]: i === arr.length - 1 ? val : a 
  }), {})

console.log(changeSetting('a>b>c', 'hello'))
console.log(changeSetting('a', 'hello'))
console.log(changeSetting('a>b>c>d>e>f>g', 'hello'))

字符串

g52tjvyc

g52tjvyc5#

function changeSetting(name, value) {
  let result;
  const attributes = name.split(">");
  result = `
{
${attributes
    .map((attribute) => attribute+":")
    .join("{")}"
 ${value}"${"}".repeat(properties.length)}`;
  return result;
}
changeSetting("a>b>c", "hello");
changeSetting("a", "hello");

字符串

相关问题