1

I have an array like this :

var startArray = [
{value: 2, label: 'label 2'},
{value: 1, label: 'label 1'},
{value: 17, label: 'label 17'},
{value: 15, label: 'label 15'}
];

And i want create the object like this:

var middleObject = {
2: 'label 2',
1: 'label 1',
17: 'label 17',
15: 'label 15'
};

And i used the code:

startArray.forEach( function(oneOption) {
  middleObject[oneOption.value] = oneOption.label;
});
enter code here

I also was tried to use this code (with the same result):

for (var oneOption in startArray) {
  middleObject[oneOption.value] = oneOption.label;
}

But problem is when i use this code i take the object like this:

var middleWrongObject = {
1: 'label 1',
2: 'label 2',
15: 'label 15',
17: 'label 17'
};

but some later i should used middleObject in the loop with the same ordering like at the firstArray. And property inside middleObject every time should be the number type. Do we have some method to set ordering for property inside the middleObject(without set property "ordering" and sort by this field later) Thanks for the help.

Vitaliy Andrusishyn
  • 2,486
  • 20
  • 28

1 Answers1

1

You could split the given array in a part for sorted keys and use an object as reference to the data.

var startArray = [{ value: 2, label: 'label 2' }, { value: 1, label: 'label 1' }, { value: 17, label: 'label 17' }, { value: 15, label: 'label 15' }],
    keys = startArray.map(a => a.value),
    object = Object.assign(...startArray.map(a => ({ [a.value]: a.label })));
    
keys.sort((a, b) => a - b);             // keys in asc order

console.log(keys.map(k => object[k]));  // access via keys
console.log(object);
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324