skip to Main Content

So i have this format of data, i’m trying to make the sub value of JSON as a key,
I don’t have any idea how to approach, Need help

var what_i_have = [
 {
  "one":"1",
  "test":[
   "two",
   "2"
  ]
 }
]


var what_i_need = [
 {
  "one":"1",
  "two":"2"
 }
]

2

Answers


  1. You can map() over the array and create new object were you keep one, and add a key from test[0] with value test[1].

    const what_i_have = [
      {
        "one":"1",
        "test":[
          "two",
          "2"
        ]
      }
    ];
    
    const what_i_need = what_i_have.map(({ one, test }) => ({ one, [test[0]]: test[1] }));
    
    console.log(what_i_need)
    Login or Signup to reply.
  2. You could check for the nested array and take the entries or the entries from the outer properties.

    const
        data = { one: "1", test: ["two", "2"] },
        result = Object.fromEntries(Object
            .entries(data)
            .map(([k, v]) => Array.isArray(v) ? v : [k, v])
        );
    
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search