Convert Javascript array of objects into one object

前端 未结 4 2122
别跟我提以往
别跟我提以往 2020-12-20 06:30

Let\'s say I have an array like this

var myarray=[{\"id\":1234, \"listtext\":open, \"prop3\":value3 ,\"prop4\": value4},
             {\"id\":1235, \"listtex         


        
相关标签:
4条回答
  • 2020-12-20 06:59

    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);
    });

    0 讨论(0)
  • 2020-12-20 07:04

    You can simply loop over the array and create a new object

    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)

    0 讨论(0)
  • 2020-12-20 07:06

    If you are using ES6 or above:

    const converted = Object.assign({}, ...myArray.map(object => ({[object.id]: object})))
    
    0 讨论(0)
  • 2020-12-20 07:06

    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)

    0 讨论(0)
提交回复
热议问题