0

I have two objects something like this and need to combine them and create an array.

        var firstData = {
          label: "Out",
          data: [
            {
              value: 2,
              title: "20-06-18 09:00",
            },
            {
              value: 5,
              title: "20-06-18 08:00",
            }
          ]
        }

        var secondData = {
          label: "In",
          data: [
            {
              value: 4,
              title: "20-06-18 09:00",
            },
            {
              value: 8,
              title: "20-06-18 08:00",
            }
          ]
        }

The result Should be an array like this an array of object where you combine the title with labels "In" and "Out".

        var result = 
        [
          {
            title: "20-06-18 09:00",
            data: [
              {
                value: 4,
                label: "In",
              },
              {
                value: 2,
                label: "Out",
              }
            ]
          },
          {
            title: "20-06-18 08:00",
            data: [
              {
                value: 8,
                label: "In",
              },
              {
                value: 5,
                label: "Out",
              }
            ]
          },
        ]

Can anyone help, please? I will try to post a fiddler example soon. Thanks in advance.

1 Answer 1

2

You can make use of reduce to achieve your task:

var firstData = { label: "Out", data: [ { value: 2, title: "20-06-18 09:00", }, { value: 5, title: "20-06-18 08:00", } ] };
var secondData = { label: "In", data: [ { value: 4, title: "20-06-18 09:00", }, { value: 8, title: "20-06-18 08:00", } ] };

var result = Object.values([firstData, secondData].reduce((acc,elem)=>{
  elem.data.forEach(({value, title})=>{
     acc[title] = acc[title] || {title, data:[]};
     acc[title].data.push({value, label:elem.label});
   });
  return acc;
},{}));

console.log(result);

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

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.