1

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: enter image description here

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?

1
  • 1
    Logically the curly bracket means an object, and you can't create an object without a key. Commented Jun 10, 2019 at 5:39

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

(side note): keys should be numeric according to the OP's output, so the key should be casted to a number.
Keys are meant to be string in an object, if keys are numeric one should use Map.
Euuh okay, as you wish, it's just that the answer would be completer in a such a way, to me ;).
3

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.