-2

I want to create dynamic JavaScript object as follows. I tried with looping the object but I failed to achieve that task.

This is the object I need:

var aposition = {
    d6: 'bK',
    d4: 'wP',
    e4: 'wK'
};

But I got Like this

 object x: "a1:"bR",b2:"bR",c6:"bP",f6:"wQ",g7:"wR",h2:"wK""

JavaScript Code

response.forEach(function (entry) {
    positionLocate += entry.Coordination + ':' + '"' + entry.Piece.Code.replace(/"/g, '') + '"' + ',';
});
halfer
  • 19,824
  • 17
  • 99
  • 186
user2710638
  • 115
  • 1
  • 3
  • 15
  • 1
    Just an advice, when you are pitching a problem, narrate it as if you are explaining it to a layman and provide facts accordingly – Rajesh Dec 26 '16 at 07:57

1 Answers1

1

Problem: You are doing a string concatenation and expecting to build an object.

Solution: You need to add key and value like this.

var aposition = {}; // declare a object
response.forEach(function (entry) {
  aposition[entry.Coordination] = entry.Piece.Code.replace(/"/g, '');// aposition[key] = value
});
Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59