0

In what way can this object be manipulated to rearrange values.

let obj = [
  {foo: 10, bar: 20},
  ["apple"],
  {foo: 30, bar: 40},
  ["pear"],
  {foo: 50, bar: 60},
  ["orange"]
]

// The output should be: 
// { "apple": { foo: 10, bar: 20 }, "pear": {...}, "orange": {...} }

I've tried the solution as provided here: loop and combine every two items

But that doesn't output the desired output.

Remi
  • 4,663
  • 11
  • 49
  • 84

3 Answers3

3

Use for loop

let obj = [{foo: 10, bar: 20},["apple"],{foo: 30, bar: 40},["pear"],{foo: 50, bar: 60},["orange"]];

var result = {};
for(let i = 0; i < obj.length; i+= 2) {
  result[obj[i+1][0]] = obj[i];
}
console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
  • Aha. Meaning: the last `i+= 2` means loop over every two iterations. Then the result is the second value (`[obj[i+1][0]]`) containing the first value (`obj[i]`). Why are the square brackets around the `[obj[i+1][0]]` exaclty? – Remi Aug 13 '18 at 08:58
  • 2
    @Remi That is to set a create a dynamic property in object. Since your property name is in a variable (*In your case, array inside array*), to get the value, you need to use square braces. Few references that might help you: `[Property Accessors](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors)`, [Dot Notation vs Brackets](https://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Rajesh Aug 13 '18 at 09:00
  • It seems that the obj.prototype.reduce method proposed by @void (and Faly) performs better. Not sure if the method I used to measure the performance is representative, but still. So I tend to accept that as the best answer. If you disagree let me know. (thanks for the info) – Remi Aug 13 '18 at 09:50
  • @Remi - `reduce` will perform `n` iterations and `for loop` will perform `n/2` iterations. Hence, for loop has better performance. – Nikhil Aggarwal Aug 13 '18 at 09:55
  • @Remi - See the difference in performance with somewhat larger data set - https://jsfiddle.net/ah7b4tjz/ – Nikhil Aggarwal Aug 13 '18 at 10:14
  • 1
    You're right. Based on your input also created a JSPerf: https://jsperf.com/rearrange-every-other-two-keys-in-object/1. Result is that the for loop performs +/- 16% better. – Remi Aug 13 '18 at 10:49
2

You can use .reduce to reduce this array into an object. See the logic below.

let obj = [{foo: 10, bar: 20},["apple"],{foo: 30, bar: 40},["pear"],{foo: 50, bar: 60},["orange"]];

const arr = obj.reduce((a, el, i, arr) => {
  if(el instanceof Array){
    a[el[0]] = arr[i-1];
  }
  return a;
}, {});

console.log(arr);
void
  • 36,090
  • 8
  • 62
  • 107
1

You can use array.reduce:

var obj = [
  {foo: 10, bar: 20},
  ["apple"],
  {foo: 30, bar: 40},
  ["pear"],
  {foo: 50, bar: 60},
  ["orange"]
];

var result = obj.reduce((m, o, i) => (Array.isArray(o) && (m[o[0]] = obj[i - 1]), m), {});

console.log(result);
Faly
  • 13,291
  • 2
  • 19
  • 37