将Javascript对象数组转换为一个对象

时间:2018-04-19 07:54:28

标签: javascript reactjs react-native

让我们说我有一个像这样的数组

var myarray=[{"id":1234, "listtext":open, "prop3":value3 ,"prop4": value4},
             {"id":1235, "listtext":open, "prop3":value3 ,"prop4": value4},
             {"id":1236, "listtext":open, "prop3":value3 ,"prop4": value4},
             {"id":1237, "listtext":open, "prop3":value3 ,"prop4": value4}];

但我想将其转换为这样的对象:

{1234:open,1235:close, 1236: pending,1237:awaiting response}

可以这样做吗?我尝试过的所有方法都只能获得最后一个键值对。

4 个答案:

答案 0 :(得分:5)

如果您使用的是ES6或以上版本:

const converted = Object.assign({}, ...myArray.map(object => ({[object.id]: object})))

答案 1 :(得分:5)

您可以简单地遍历数组并创建一个新对象

var myarray=[{"id":1234, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'},
             {"id":1235, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'},
             {"id":1236, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'},
             {"id":1237, "listtext":'open', "prop3":'value3' ,"prop4": 'value4'}];
const res = {};
myarray.forEach(obj => {
    res[obj.id] = obj.listtext;
})
console.log(res)

答案 2 :(得分:1)



var myarray = [
  { id: 1234, listtext: 'open' },
  { id: 1235, listtext: 'closed' },
  { id: 1236, listtext: 'pending' },
  { id: 1237, listtext: 'open' }
]

var output = myarray.reduce(function (acc, item) {
  acc[item.id] = item.listtext
  return acc
}, {})

console.log(output)




答案 3 :(得分:0)

var myarray=[{"id":1234, "listtext":"open", "prop3":'value3' ,"prop4": 'value4'},
             {"id":1235, "listtext":"closed", "prop3":'value3' ,"prop4": 'value4'},
             {"id":1236, "listtext":"pending", "prop3":'value3' ,"prop4": 'value4'},
             {"id":1237, "listtext":"open", "prop3":'value3' ,"prop4": 'value4'}];

var myObjects = [];  // create an empty array to hold the converted objects.


// loop through the array to convert them one by one
myarray.forEach(function(element) {
  var obj = {};    // create an empty object
  obj[element.id] = element.listtext;
  myObjects.push(obj);  // add the object to the array
});


myObjects.forEach(function(object){
   console.log(object);
});