0

I have got array of nested array of objects .

  const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]

I want to convert array to this format of objects and I want to get this output

 let permission ={

       group:["1"],
       topGroup:["2"]
     }

How can I do this ?

3
  • 1
    You can use reduce or map method for data array. But what is the algorithm to become "2" from "12"?
    – Leonid
    Mar 22, 2020 at 10:36
  • const data = [ {group: ["1"]}, {topGroup: ["12"]} ] let da = Object.fromEntries(data.map((key)=>Object.entries(key)[0])) I got value when when My input data , but I could not understand when I add object inside array . how can I get my expected output
    – sujon
    Mar 22, 2020 at 10:39
  • I just edited . can you see
    – sujon
    Mar 22, 2020 at 10:40

4 Answers 4

2

const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]

const converted = data.reduce((a,b) => {
   const onlyKey = Object.keys(b)[0];
   a[onlyKey] = b[onlyKey].map(i => i.label);
   return a;
}, {})

console.log(converted)

1
2

const data = [ {group: [{label:"1"}]}, {topGroup: [{label:"2"}]} ]
let permission = {};
data.forEach(val =>{
  for(prop in val){
    permission[prop] = [val[prop][0]["label"]]
  }
})

console.log(permission)

Give this a upvote if this is what you want.

1

Assuming the data is going to have labels as in that format forever, you could use something like that

const data = [{"group":[{"label":"1"}]},{"topGroup":[{"label":"12"}]}];

// The dict variable under here is the second parameter of reduce that I passed it `{}`.
// The ind variable is the data at the index of the array.
var newData = data.reduce(function(dict, ind){
    // You basically get the keys and the values and put them in place
    // and return the last state to the reduce function.
    dict[Object.keys(ind)] = Object.values(ind)[0][0]["label"];
    return dict;
}, {})

console.log(newData)

1

Use destructuring and Object.fromEntries.

const data = [{ group: [{ label: "1" }] }, { topGroup: [{ label: "2" }] }];

const permission = Object.fromEntries(
  data.map(item => {
    const [[key, [obj]]] = Object.entries(item);
    return [key, Object.values(obj)];
  })
);

console.log(permission);

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.