将对象属性值推送到数组

时间:2021-05-22 14:44:58

标签: javascript arrays json

使用 JS 根据 JSON 对象中存在的键数将对象转换为数组。

实际对象

  values: [
        {
          Label: "label1",
          Value: "10",
        },
        {
          Label: "label2",
          Value: "11",
        },
        {
          Label: "label3",
          Value: "12",
        },
      ],
    };

我希望实际输出是这样的

label:['label1','label2','label3']
value:['10','11','12']

使用 javascript 或响应。 提前致谢

5 个答案:

答案 0 :(得分:0)

最简单、最直观的方法就是使用两个 =arrayformula(query({array_constrain({if(A2:A<>"",A$1,),A2:A},max(counta(A:A),MAX(IF(A:B<>"",ROW(A:B)))),2);if(B2:B<>"",B$1,),B2:B},"order by Col2 desc limit 3",0)) 循环,就像这样,它们会自动构建对象。这个答案的好处是它适用于具有任意数量不同键的对象——没有键名是硬编码的,所以它完全可以适应。

        string command = $"/C start \"\" \"C:/Program Files/Amazon/AWSCLIV2/aws.exe\" --version";

        ProcessStartInfo info = new ProcessStartInfo();
        info.FileName = "cmd.exe";
        info.Arguments = command;
        info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;

        var process = new Process();
        process.StartInfo = info;
        process.Start();

答案 1 :(得分:0)

您可以使用数组的 map 函数并从输入数组中返回标签和值。

let  values = [
        {
          Label: "label1",
          Value: "10",
        },
        {
          Label: "label2",
          Value: "11",
        },
        {
          Label: "label3",
          Value: "12",
        },
      ]

let value = values.map(v => v.Value)
let label = values.map(v => v.Label)

console.log(value)
console.log(label)

答案 2 :(得分:0)

你可以像下面这样使用 forEach

 let  values = [
        {
          Label: "label1",
          Value: "10",
        },
        {
          Label: "label2",
          Value: "11",
        },
        {
          Label: "label3",
          Value: "06",
        },
         {
          Label: "label4",
          Value: "25",
        }
      ]
      let valueArray =[]
      let labels =[]
      values.forEach((value)=>{
      valueArray.push(value.Value)
      labels.push(value.Label) 
      })
       
     let finalObject = {label:labels,value:valueArray}
console.log(valueArray)
console.log(labels)
console.log(finalObject)

答案 3 :(得分:0)

let obj = {
    values: [
        {
            Label: "label1",
            Value: "10",
        },
        {
            Label: "label2",
            Value: "11",
        },
        {
            Label: "label3",
            Value: "12",
        }
    ]
};

let output = {
    label: [],
    value: []
};

for (const [key, value] of Object.entries(obj.values)) {
    output.label.push(value.Label)
    output.value.push(value.Value)
}

console.log("output::", output)

答案 4 :(得分:0)

您可以一次减少对象:

const values = [ { Label: "label1", Value: "10", }, { Label: "label2", Value: "11", }, { Label: "label3", Value: "12", } ];

let reduced =  values.reduce((total, curr) => {
    total.label.push(curr.Label)
    total.value.push(curr.Value)

    return total
}, {"label": [], "value": []})

console.log(reduced.label)
console.log(reduced.value)

相关问题