javascript数组对象转换一个键,数组值单个对象

时间:2018-11-22 11:49:53

标签: javascript underscore.js lodash

我有一个这样的对象:

[ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
] 

我想要:

{"number": [12, 40], "string": ["hi", "bye"]}

或者:

{"number": "12,40", "string": "hi,bye"}

5 个答案:

答案 0 :(得分:2)

您可以使用Array.prototype.reduce()

  

reduce()方法在数组的每个成员上执行reducer函数(由您提供),从而产生单个输出值。

带连接字符串的解决方案:

var data = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
] 
data = data.reduce((a,c)=>{
  a.number = a.number + ',' +c.number;
  a.string = a.string + ',' +c.string;
  return a;
});
console.log(data);

阵列解决方案:

var data = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
]

data = data.reduce((a,c)=>{
  a.number.push(c.number);
  a.string.push(c.string);
  return a;
}, {number:[],string:[]});
console.log(data);

答案 1 :(得分:1)

我这样做是这样的:

let array = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
];

let resultObject = {
    numbers: [],
  strings: []
}

for (let element of array) {
 resultObject.numbers.push(element.number);
 resultObject.strings.push(element.string);
}

console.log(resultObject);

希望它会有所帮助:)

答案 2 :(得分:0)

您可以使用Array.reduce()

var arr = [ 
    { "number": 12, "string": "hi"},
    { "number": 40, "string": "bye"}
];
var res = arr.reduce((acc, item)=>{
  if(acc.number && acc.string){
    acc.number.push(item.number);
    acc.string.push(item.string);
  } else {
    acc = {
      number: [item.number],
      string: [item.string]
    }
  }
  return acc;
}, {});
console.log(res);

答案 3 :(得分:0)

您可以缩小数组和对象的实体,并使用它们的键将所有值收集到数组中,而无需使用硬编码的属性。

var array = [{ number: 12, string: "hi" }, { number: 40, string: "bye" }],
    result = array.reduce(
        (r, o) => Object.entries(o).reduce(
            (s, [k, v]) => ((s[k] = s[k] || []).push(v), s),
            r
        ),
        {}
    );

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 4 :(得分:0)

您可以使用lodash的_.mergeWith()来组合它们:

const arr = [{ "number": 12, "string": "hi"}, { "number": 40, "string": "bye"}];

const result =_.mergeWith({}, ...arr, (s = [], o) => [...s, o]);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>