0

I would like to understand what am I doing wrong here. The problem is simple: I get an array in a response and I would need to access to its elements by name. Therefore I use Map to create a pair of Metric and Value. Subsequently, I use JSON stringify which I thought would be enough. But when I try to access the element (array.Speed), I am getting Undefined.

var response=[
  {
    metric: "Speed",
    value: "145",
  },
  {
    metric: "Deceleration",
    value: "76.5",
  }
];
 let array=[];

response.map(m=> {
            array.push({
                [m.metric]:m.value
            });

        });


var j=JSON.stringify(array);
console.log(j.Speed); //UNDEFINED
var js=JSON.parse(j);
console.log(js.Speed); //UNDEFINED

Stringify and access, converting to JSON later even, as described.

  • 1
    I don't see `.coverage` defined anywhere. – chovy Dec 08 '22 at 10:18
  • where did you define `.coverage` exactly? – Moussa Bistami Dec 08 '22 at 10:19
  • @chovy My bad, I made the names more clear for the example, I changed that. –  Dec 08 '22 at 10:19
  • map doesn't mutate...you need to assign it to a new array. – chovy Dec 08 '22 at 10:22
  • Are you trying to get the object `{ Speed: 145, Deceleration: 76.5 }`? That’s just `const object = Object.fromEntries(response.map(({ metric, value }) => [ metric, Number(value) ])); console.log(object.Speed);`. You want a keyed collection, not an indexed collection, so `let array = []` is not useful. Also, what are you trying to do with JSON methods? – Sebastian Simon Dec 08 '22 at 10:24
  • 1
    `j` is a string. Strings don't have a `Speed` property. `console.log(j.Speed);` doesn't make sense. `js` is an array. Arrays don't have a `Speed` property. `console.log(js.Speed);` doesn't make sense. – jabaa Dec 08 '22 at 11:33
  • @SebastianSimon Thanks, that is it! Can I get the key-value pair easily back, i.e. while iterating through? Simple "for" returns just the key. –  Dec 08 '22 at 11:43

0 Answers0