2

I'm facing some issue in for loop while creating an object from array of object.I have an array as this in node js app:

[
        {
            "Material": "113/133",
            "Name": [
                {
                    "name": "WELD1",
                    "value": 27520
                },
                {
                    "name": "WELD2",
                    "value": 676992
                },
                {
                    "name": "WELD3",
                    "value": 421
                }
            ]
        },
        {
            "Material": "150/300",
            "Name": [
                {
                    "name": "WELD1",
                    "value": 1441
                },
                {
                    "name": "WELD2",
                    "value": 555
                },
                {
                    "name": "WELD3",
                    "value": 100992
                }
            ]
        }
    ]

I want to return object like this which contains all the Material as array, Name and there value in array of object like this:

{
    Material: ["113/133", "150/300"],
    datasets: [
        {
            label: "WELD1",
            data: [27520,1441]
        },
        {
            label: "WELD2",
            data: [676992,555]
        },
                {
            label: "WELD3",
            data: [100,20,0]
        }
    ]
}

I want to get result using for loop.

3
  • Please share the code you tried as a minimal reproducible example and explain what youa re having trouble with. Commented Jun 1, 2018 at 9:25
  • for (var i = 0; i < result.length; i++) { sku_label[i] = result[i].Material; for (var j = 0; j < result[i].Name.length; i++) { } } result is the the array of object Commented Jun 1, 2018 at 9:28
  • No, add a minimal reproducible example to your post as an edit Commented Jun 1, 2018 at 9:29

4 Answers 4

2

you can use .reduce() and do something like this:

var arr = [
    {
        "Material": "113/133",
        "Name": [
            {
                "name": "WELD1",
                "value": 27520
            },
            {
                "name": "WELD2",
                "value": 676992
            },
            {
                "name": "WELD3",
                "value": 421
            }
        ]
    },
    {
        "Material": "150/300",
        "Name": [
            {
                "name": "WELD1",
                "value": 1441
            },
            {
                "name": "WELD2",
                "value": 555
            },
            {
                "name": "WELD3",
                "value": 100992
            }
        ]
    }
];

var newArr = arr.reduce((acc, ob) => {
  for (var key in ob)
     if(typeof acc[key] === 'object')
         acc[key] = acc[key] ? acc[key].concat(ob[key]) : [ob[key]];
     else
         acc[key] ? acc[key].push(ob[key]) : acc[key] = [ob[key]];
  return acc;
}, {}); 

console.log(newArr);

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

Comments

1

let array = [
        {
            "Material": "113/133",
            "Name": [
                {
                    "name": "WELD1",
                    "value": 27520
                },
                {
                    "name": "WELD2",
                    "value": 676992
                },
                {
                    "name": "WELD3",
                    "value": 421
                }
            ]
        },
        {
            "Material": "150/300",
            "Name": [
                {
                    "name": "WELD1",
                    "value": 1441
                },
                {
                    "name": "WELD2",
                    "value": 555
                },
                {
                    "name": "WELD3",
                    "value": 100992
                }
            ]
        }
    ]

let answer = {Material: [], datasets: []}

array.forEach(x => {
  answer.Material.push(x.Material);
  
  x.Name.forEach(na => {
    let object = answer.datasets.find(obj => obj.label === na.name) || {label: "", data: []};
    
    if(object.label === ""){
    	object.label = na.name;
      object.data.push(na.value);
      answer.datasets.push(object);
    }else{
    	object.data.push(na.value)
    }
  });
  
  
});

console.log(answer);

The above is alternative solution using forEach instead of reduce

Comments

0

Use of Array.reduce to build your new data structure using data you have

const start = [{
    "Material": "113/133",
    "Name": [{
        "name": "WELD1",
        "value": 27520
      },
      {
        "name": "WELD2",
        "value": 676992
      },
      {
        "name": "WELD3",
        "value": 421
      }
    ]
  },
  {
    "Material": "150/300",
    "Name": [{
        "name": "WELD1",
        "value": 1441
      },
      {
        "name": "WELD2",
        "value": 555
      },
      {
        "name": "WELD3",
        "value": 100992
      }
    ]
  }
];

const end = start.reduce((tmp, {
  Material,
  Name,
}) => {
  // Handle the material
  // If it do not exist in the array, push it
  if (!tmp.Material.includes(Material)) {
    tmp.Material.push(Material);
  }

  // Handle the datasets
  // Look at each Name
  Name.forEach(({
    name,
    value,
  }) => {
    // Can we find the label?
    const labelFind = tmp.datasets.find(y => y.label === name);

    // If we can't find the label, create a new dataset
    if (!labelFind) {
      tmp.datasets.push({
        label: name,

        data: [
          value,
        ],
      });

      return;
    }

    // If we has found it push new value in the dataset 
    labelFind.data.push(value);
  });

  return tmp;
}, {
  Material: [],
  datasets: [],
});

console.log(end);

Comments

0
// This is the old fashioned way.
// Iterate over whole array, 
// make a map, push value where 'name' is found in map
// later iterate over this map - dataMap - and form required datasets array.

var Material = [];
var dataMap = {};

arr.forEach(obj => {
    Material.push(obj.Material);
    obj.Name.forEach(item => {
        if(dataMap[item.name]){
            dataMap[item.name].push(item.value);
        }
        else {
            dataMap[item.name] = [item.value];
        }
    });
});

var datasets = [];
Object.keys(dataMap).forEach(label => {
    datasets.push({
        label: label,
        data: dataMap[label]
    });
});

var result = {
    Material: Material,
    datasets: datasets
}

console.log(result);

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.