【问题标题】:Convert json to other json structure将json转换为其他json结构
【发布时间】:2018-11-07 11:35:28
【问题描述】:

我有一个具有这种结构的对象数组:

const treeData = [
  { 0: ["0-0", "0-1"] },
  { 1: ["1-0", "1-1"] }
]

可能更深,但数组数据总是 json 或字符串

const treeData = [
  { 0: ["0-0", "0-1"] },
  { 1: ["1-0", "1-1"] },
    2,
    3
]

我想得到这样的东西:

const treeDataResult = [
  {
    label: "0",
    value: "0",
    children: [
      {
        label: "0-0",
        value: "0-0"
      },
      {
        label: "0-1",
        value: "0-1",
      }
    ]
  },
  {
    label: "1",
    value: "1",
    children: [
      {
        label: "1-0",
        value: "1-0",
      },
      {
        label: "1-1",
        value: "1-1",
      }
    ]
  },
  { 
    label: "2",
    value: "2"
  },
  { 
    label: "3",
    value: "3"
  }
]

我现在的代码是这样的:

const treeData = [
      { "0": ["0-0", "0-1"] },
      { "1" : ["1-0", "1-1"] }
    ];

const convertNode = (parentNode) =>
  parentNode.map(
    childnode => {
      if (typeof(childNode) === 'string')
        return {
          label: childNode,
          value: childNode
        }
      else
        return
      childNode.map((key, val) =>
        ({
          label: key,
          value: key,
          children: convertNode(val)
        })
      )
    }
  )

var treeDataResult = convertNode(treeData);
console.log(treeDataResult);

【问题讨论】:

  • 在您当前的代码中什么不起作用?
  • 23typeof 将是 "number",而不是 "string"。此外,如果您的节点是一个对象,它可能不是一个数组 - 您需要实际获取您正在 (ab) 使用的单个键作为标签。
  • 返回后不能有回车。如果你想在一个新的行上做:return ( (new line here ok)childNode.map... )
  • 您将 JavaScript 对象误认为是 JSON。她们不一样。 JSON总是是一个字符串。
  • 当键是变量时,像 { 0 : "foo" }{ 1: "bar" } 这样的对象是不好的。为了让您的程序提取密钥的值,必须使用Object.keysObject.entries。与已知 keyvalue 之类的 { key: 0, value: "foo" } 相比,提取每个值只需读取它们各自的属性即可。

标签: javascript arrays ecmascript-6 functional-programming


【解决方案1】:

如果你的数据的形状是正确的我已经使用 reduce 和 map 将数据变成正确的形状和 rest 运算符,以便对象在一个数组中

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

const treeData = [
  {
    0: ["0-0", "0-1"]
  },
  {
    1: ["1-0", "1-1"]
  },
  {
    2: null
  },
  {
    3: []
  },
  {
    4: ["0-1"]
  }
]

const changeShape = data => {
  return data.reduce((prev, curr) => [...prev, ...shape(curr)], []);
}

const shape = item => Object.keys(item).map(key => data(item, key));

const data = (item, key) => {
  return !item[key] || !item[key].length > 0 ?
    labelValue(key) : 
    {
      ...labelValue(key),
      children: item[key].map(i => labelValue(i))
    }
}

const labelValue = v => {
  return {
    label: v,
    value: v
  }
}

console.log(changeShape(treeData))

【讨论】:

    【解决方案2】:

    原始解决方案

        const treeData = [
              { 0 : ["0-0", "0-1"] },
              { 1 : ["1-0", "1-1"] }
            ]
            
            let treeDataResult = [];
            
            
            for(i = 0; i < treeData.length; i++) {
              let current = treeData[i],
              label = Object.getOwnPropertyNames(current),
            
              obj = {
                label: label,
                value: label,
                children: []
              }
              
             for(j = 0; j < current[i].length; j++) {
                let childData = current[i][j],
                child = {
                label : childData,
                value : childData
              } 
              obj.children.push(child) 	
             }
            treeDataResult.push(obj)
            }
    
           console.log(JSON.stringify(treeDataResult, null, 4));

    【讨论】:

      【解决方案3】:
      const treeData = [
        { "0": ["0-0", "0-1"] },
        { "1" : ["1-0", "1-1"] }
      ];
      
      const convertNode = (parentNode) => {
        console.log(parentNode)
        return parentNode.map(
          childNode => {
            if (typeof childNode === 'string')
              return {
                label: childNode,
                value: childNode
              }
            else
              return {
                label: Object.entries(childNode)[0][0],
                value: Object.entries(childNode)[0][0],
                children: convertNode(Object.entries(childNode)[0][1])
              }
          }
        )
      }
      

      【讨论】:

        【解决方案4】:

        如果使用JSON.parse获取数据,可以试试这样:

        var j = '[ { "0": ["0-0", "0-1"] }, { "1": ["1-0", "1-1"] }, 2, 3 ]'
        
        var o = JSON.parse(j, (k, v) => (k = v.constructor) === Array ? v : 
          k !== Object ? ({ label: v, value: v }) :
          ({ label: k = Object.keys(v)[0], value: k,  children: v[k] }) )
        
        console.log( o )

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-17
          • 1970-01-01
          • 2021-12-10
          • 1970-01-01
          • 2017-10-01
          • 2021-10-18
          • 2011-12-21
          • 2016-01-11
          相关资源
          最近更新 更多