1

My data is currently stored in this format:

{
   "Site1":{
      "week":[
         {
            "access":1
         },
         {
            "access":8
         }
      ]
   },
   "Site2":{
      "week":[
         {
            "access":16
         }
      ]
   },
   "Site3":{
      "week":[
         {
            "access":2
         },
         {
            "access":6
         },
         {
            "access":2
         }
      ]
   }
}

And I need to convert it into this format:

[
   {
      "id":"Site1",
      "access":[1,8]
   },
   {
      "id":"Site2",
      "access":[16]
   },
   {
      "id":"Site3",
      "access":[2,6,2]
   }
]

As you can see, I also need to take the keys (site name) and make them the "id" values.

Any ideas on how I can do this in JavaScript (I'm using angular v9)? I'm not very good at restructuring that type of data.

3 Answers 3

3

You can first take entries and then map it:

var data={ "Site1":{ "week":[ { "access":1 }, { "access":8 } ] }, "Site2":{ "week":[ { "access":16 } ] }, "Site3":{ "week":[ { "access":2 }, { "access":6 }, { "access":2 } ] }};

var result = Object.entries(data).map(([k,v])=>({id:k, access: v.week.map(p=>p.access)}));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

2
  1. Object.keys()
  2. map()

const data = {
    Site1: {
        week: [
            {
                access: 1,
            },
            {
                access: 8,
            },
        ],
    },
    Site2: {
        week: [
            {
                access: 16,
            },
        ],
    },
    Site3: {
        week: [
            {
                access: 2,
            },
            {
                access: 6,
            },
            {
                access: 2,
            },
        ],
    },
};

const result = Object.keys(data).map(key => ({
    id: key,
    access: data[key].week.map(w => w.access),
}));

console.log(result);

1 Comment

I really appreciate your help thanks a lot! It worked for me
2

you can simply use this code for your desired result.

Object.keys(data).map(key => (
    {
        id: key,
        access: data[key].week.map(obj => obj.access),
    }
))

Let me know if you face any issue.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.