【问题标题】:Javascript array into string conversionsJavascript数组到字符串的转换
【发布时间】:2021-01-04 07:24:18
【问题描述】:

我有这样的javascript数组

let attributeSet = [ 
    {
        "name" : "Capacity",
        "value" : "1 TB",
        "id" : 3
    }, 
    {
        "name" : "Form Factor",
        "value" : "5 inch",
        "id" : 4
    },
    {
        "id" : 5,
        "name" : "Memory Components",
        "value" : "3D NAND",
    }
]

格式应为 id-value 对。 id的顺序也应该是递增的。像这样


output = 3-1 TB | 4-5 inch | 5-3D Nand

谁能帮忙?

【问题讨论】:

    标签: javascript arrays json string


    【解决方案1】:

    在 ES6 中你可以试试这个:

    let output = attributeSet.sort((a, b) => a.id - b.id).map(i => `${i.id}-${i.value}`).join(' | ');
    

    【讨论】:

    【解决方案2】:

    使用Array.sort()根据id对数组进行排序并使用Array.join()加入它们

    const attributeSet = [ 
        {
            "name" : "Capacity",
            "value" : "1 TB",
            "id" : 3
        }, 
        {
            "name" : "Form Factor",
            "value" : "5 inch",
            "id" : 4
        },
        {
            "id" : 5,
            "name" : "Memory Components",
            "value" : "3D NAND",
        }
    ]
    
    attributeSet.sort((a, b) => a.id - b.id);
    const output = attributeSet.map(item => item.id + '-' + item.value).join(" | ")
    console.log(output);

    【讨论】:

      【解决方案3】:

      您可以先按 id 对数组进行排序,然后从该排序后的数组迭代并创建新数组,

      attributeSet = [ 
          {
              "name" : "Capacity",
              "value" : "1 TB",
              "id" : 3
          }, 
          {
              "name" : "Form Factor",
              "value" : "5 inch",
              "id" : 4
          },
          {
              "id" : 5,
              "name" : "Memory Components",
              "value" : "3D NAND",
          }
      ]
      
      attributeSet.sort((a,b) => parseInt(a.id) - parseInt(b.id));
      let res = attributeSet.map(item => {
        return item.id+'-'+item.value;
      })
      console.log(res.join(' | '));

      【讨论】:

        【解决方案4】:

        使用 reducetemplate string 构建所需的 id-value 对字符串

        const getString = (arr) =>
          arr
            .sort((a, b) => a.id - b.id)
            .reduce((acc, { id, value }, i) => `${acc}${i ? " | " : ""}${id}-${value}`, '');
        
        let attributeSet = [
          {
            name: "Capacity",
            value: "1 TB",
            id: 3,
          },
          {
            name: "Form Factor",
            value: "5 inch",
            id: 4,
          },
          {
            id: 5,
            name: "Memory Components",
            value: "3D NAND",
          },
        ];
        
        console.log(getString(attributeSet));

        【讨论】:

          猜你喜欢
          • 2022-01-23
          • 1970-01-01
          • 2017-10-27
          • 2015-02-21
          • 1970-01-01
          相关资源
          最近更新 更多