-1

I am trying to create new object by looping the data;

let a =[{"name":"test","age":12,"std":"1std"},{"name":"test2","age":14,"std":"2nd"}, {"name":"test3","age":11,"std":"3rd"}];

for my above array i am trying to get following output;

              {
                 "1":{"name":"test","age":"12"},
                 "2":{"name":"test2","age":"14"},
                 "3":{"name":"test3","age":"11"}
               }

below i am trying like this.please help to form above object using map();

             a.map(stu => {
                     stu.std={"name":stu.name,"age":stu.age} 
             })
Barmar
  • 741,623
  • 53
  • 500
  • 612
Wilson
  • 11
  • 4
  • Does this answer your question? [Dynamically access object property using variable](https://stackoverflow.com/questions/4244896/dynamically-access-object-property-using-variable) – Justinas Aug 30 '21 at 16:21
  • 1
    Arrays are not `key:value`. Your desired result should be an object, not array. – Barmar Aug 30 '21 at 16:22

1 Answers1

0

You're setting the std property of each student to a nested object. You need to use the stu.std property as the key of a new object that holds the result.

let a =[{"name":"test","age":12,"std":"1st"},{"name":"test2","age":14,"std":"2nd"}, {"name":"test3","age":11,"std":"3rd"}];

let result = {};

a.forEach(stu => result[stu.std.replace(/\D/g, '')] = {name: stu.name, age: stu.age});

console.log(result);

stu.std.replace(/\D/g, '') will remove the non-numeric characters of the std property to get the desired keys in the result.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • thank you... actullay i am getting this errror message as "Arrow function should not return assignment" – Wilson Aug 30 '21 at 16:34
  • That sounds like an eslint warning, not a JavaScript error. And it's inappropriate here, because `forEach()` doesn't use the return value, so it doesn't matter. – Barmar Aug 30 '21 at 16:35