-3

I have

let array = ['mango', 'mango_shake','banana', 'banana_shake', 'cherry', 'cherry_shake', 'Strawberry', 'Strawberry_shake', ...n];

What i want to do is:

let target = [{'fruit': 'mango', 'drink': 'mango_shake'}, 
{'fruit': 'banana', 'drink': 'banana_shake'}, ...n];

How can i do it?

Axnyff
  • 9,213
  • 4
  • 33
  • 37
Angi90
  • 1
  • 4
  • 9
    What did you try? A simple loop should work – Axnyff Feb 22 '18 at 17:21
  • 3
    How is this array generated? Like Axnyff said, a simple looping structure could do this, but its probably better if you could avoid mixing two different things into a single array in the first place. – Kallmanation Feb 22 '18 at 17:22
  • 1
    When solving problems like this, it helps to think about how you would solve the problem yourself. If I gave you a list of words similar to your array, what steps would you take to create the list of objects? Write a description in words before you even attempt to write any code. – Code-Apprentice Feb 22 '18 at 17:29
  • Possible duplicate of [Convert Array to Object](https://stackoverflow.com/questions/4215737/convert-array-to-object) – Arsalan Akhtar Feb 22 '18 at 17:31
  • A simple loop is just fine. I cant avoid mixing because i get from database string. Arsalan Akhtar, i see that post. – Angi90 Feb 22 '18 at 17:54

3 Answers3

2

You can simply loop through array and create an array of object like this

let array = ['mango', 'mango_shake', 'banana', 'banana_shake', 'cherry', 'cherry_shake', 'Strawberry', 'Strawberry_shake'];
var res = [];

for (var i = 0; i < array.length; i = i + 2) {
  var ob = {};
  ob.fruit = array[i];
  ob.drink = array[i + 1];
  res.push(ob);
}

console.log(res);

Note: This answer assumes the fruit and its corresponding drink are always right beside each other in the array. This will give wrong answers if items are out of order.

StudioTime
  • 22,603
  • 38
  • 120
  • 207
Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31
0

Just iterate over your original array until it is empty and take out pairs and map them to objects:

 const result = [];

 while(array.length)
   result.push((([fruit, drink]) => ({fruit, drink}))(array.splice(0, 2));

(In case this is your homework: i think it will be harder to explain to your teacher how it works instead of just trying it on your own :))

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • **Note:** This answer assumes the fruit and its corresponding drink are always right beside each other in the array. This will give wrong answers if items are out of order. – Kallmanation Feb 22 '18 at 17:26
0

You can iterate over the array to combine every other item

let target = {};
array.forEach( (curr, indx, arr) => {
    if (indx %2 == 1) {
        target[arr[indx-1]] = curr
    }
});
Chic
  • 9,836
  • 4
  • 33
  • 62
hashedram
  • 813
  • 7
  • 14