0

I have a variable of the form:

var data=[
{
    start:22,
    end: 8
},
{
    start:60,
    end: 43       
},
{
    start: 35,
    end: 55
},
{
    start:25,
    end:40
}
];

I want to map it to look like this

var newData = { 22:8, 60:43, 35:55, 25:40};

Is this possible? I mainly just want to use the start numbers as a key to access the end numbers without using search. I have tried to do this:

 var mapData = data.map(function(data){
  var x = {};
  x[data.start]=data.end;
  return x;
});

but it gives: 0 : {22: 8} 1 : {60: 43} 2 : {35: 55} 3 : {25: 40} which means i have to use 0, 1,2, 3 as indices.

5
  • 2
    please add a valid result. Commented Nov 7, 2017 at 9:04
  • 3
    newData is not a valid object. Commented Nov 7, 2017 at 9:05
  • 1
    Did you mean { 22:8, 60:43, 35:55, 25:40 }? Commented Nov 7, 2017 at 9:06
  • impossible you cant write like "{8}" Commented Nov 7, 2017 at 9:06
  • @nnnnnn Yes I meant that, i'll edit to say this. Commented Nov 7, 2017 at 9:08

2 Answers 2

4

Only Array#map does not work in this case, because without post processing, you get a single array with objects. You need to combine all objects into a single object.

With Object.assign and spread syntax ..., you get a single array with all properties from the objects in the array.

var data = [{ start: 22, end: 8 }, { start: 60, end: 43 }, { start: 35, end: 55 }, { start: 25, end: 40 }],
    result = Object.assign(...data.map(({ start, end }) => ({ [start]: end })));
    
console.log(result);

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

1 Comment

Thanks a lot Nina. I was not aware of the spread syntax, since I'm still a beginner to javascript.
3

You can use array.reduce:

var data=[
{
    start:22,
    end: 8
},
{
    start:60,
    end: 43       
},
{
    start: 35,
    end: 55
},
{
    start:25,
    end:40
}
];

var res = data.reduce((m, o) => { 
  m[o.start] = o.end; 
  return m;
}, {});

console.log(res);

1 Comment

Thank you, I wasn't aware of these methods.

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.