0

I'm trying to create a Array using json objects. But the last object is repeating in the array. I've mentioned that in the below code output. Can anyone help me finding the solution of this problem

This is the code

let list = [
    {
    'title':'alfa',
    'item':'box',
    'count':2
    },
    {
    'title':'beta',
    'item':'ball',
    'count':4
    }
]
let ev = {}
let ev_arr = []
for(let i in list){
    ev.title = list[i].title
    ev.item = list[i].item
    ev_arr.push(ev)
}

console.log(ev_arr)

My output I got

[
    {
    'title':'beta',
    'item':'ball'
    },
    {
    'title':'beta',
    'item':'ball'
    }
]

Expected Output

[
    {
    'title':'beta',
    'item':'ball'
    },
    {
    'title':'alfa',
    'item':'box'
    }
]
Ravi_Djpy
  • 11
  • 4

1 Answers1

2

You only ever have one object:

let ev = {}

The loop just over-writes the properties on that same object and re-adds that same object to the array. But there's still only ever one object.

Instead, create a new object in each iteration of the loop:

let list = [
    {
    'title':'alfa',
    'item':'box',
    'count':2
    },
    {
    'title':'beta',
    'item':'ball',
    'count':4
    }
]
let ev_arr = []
for(let i in list){
    let ev = {}    // <----- here
    ev.title = list[i].title
    ev.item = list[i].item
    ev_arr.push(ev)
}

console.log(ev_arr)

To be honest, the code can be drastically simplified in general:

let list = [
  {
    'title':'alfa',
    'item':'box',
    'count':2
  },
  {
    'title':'beta',
    'item':'ball',
    'count':4
  }
];
let ev_arr = list.map(l => ({ title: l.title, item: l.item }));
console.log(ev_arr)

In this case you don't even need to manually create any objects or arrays as placeholders. You're just projecting an array into a new array using .map().

David
  • 208,112
  • 36
  • 198
  • 279