简体   繁体   中英

How to set array key as it's index in javascript/node js

I have an array of objects like this :

var kvArray = [ 
   { 
       number: '123',
       duration: '00:00:00' 
   },
   { 
      number: '324',
      duration: '00:00:00' 
   }]

I want to generate a new array from the above array such that the number key becomes the index.

This is what I tried

 var kvArray = [ { number: '123', duration: '00:00:00' }, { number: '324', duration: '00:00:00' }] var reformattedArray = kvArray.map(obj =>{ var rObj = {}; rObj[obj.number] = obj.duration; return rObj; }); console.log(reformattedArray) 

The above output looks like this in the console with 0 and 1 as the index: 在此处输入图片说明

Instead I want the output array to be like this :

123: {"00:00:00"}
324: {"00:00:00"}

such that instead of 0 , 1 as the index I have 123 and 324 as the index. So that if write test_array[123] in my code I should be able to get 00:00:00 in the output. Is it possible to achieve what I'm trying to do here? Suggest better ways how this can be done

How do I do this?

You can use array#map with Object.assign() to create the desired output.

 const data = [ { number: '123', duration: '00:00:00' }, { number: '324', duration: '00:00:00' } ], result = Object.assign(...data.map(({number, duration}) => ({[number]: duration}))); console.log(result); 

In case number values will be unique in your array, you can use .reduce() to create a map object like shown below:

 const data = [ { number: '123', duration: '00:00:00' }, { number: '324', duration: '00:00:00' } ]; const map = data.reduce((r, { number:k, duration:v }) => (r[k] = v, r), {}); console.log(map); 

reformattedArray =[]
tempHash = kvArray.reduce(function(i,j){
    return $.extend(i,j)
})
for(i in tempHash) {
    reformattedArray[i] = tempHash[i]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM