0

My object is like this.

var myData = [
   { 123: 1}, 
   { 123: 2}, 
   { 124: 3}, 
   { 124: 4}
];

and the expected result is:

var myDataNew = [
    {123: [1, 2]}, 
    {124: [3,4]}
];

How to achieve this using javascript?

2
  • There is no JSON in your question, just JavaScript, and you are trying to remove objects from an array. Commented Oct 17, 2018 at 10:31
  • 1
    Can you improve your question title then? What you're looking for is a reducer. What have you attempted so far? Commented Oct 17, 2018 at 10:33

3 Answers 3

1

You can try this, with your current structure, where each object in the myData array has only one member.

const myData = [
    { 123: 1},
    { 123: 2},
    { 124: 3},
    { 124: 4}
];

const groupDuplicates = (arr) =>
    
    arr.reduce((acc, val) => {
        
        const key = Object.keys(val).toString();
        
        const item = acc.find((item) => Object.keys(item).toString() === key);

        if (!item) acc.push({ [key]: [val[key]]});

        else item[key].push(val[key]);

        return acc;
    }, []);

console.log(groupDuplicates(myData));

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

Comments

0

You can use this code:

var myData = [
               { 123: 1}, 
               { 123: 2}, 
               { 124: 3}, 
               { 124: 4}
             ];
/*
var myDataNew = [
    {123: [1, 2]}, 
    {124: [3,4]}
];
            */
var keys = myData.map(current=>Object.keys(current)[0]);
//console.log(keys);//(4) ["123", "123", "124", "124"]
var result = [];
keys.forEach((current,index)=>{
  //findIndex in result
  let id = result.findIndex(c=>{
    if(c[current])
      return c;
  });
  // not find
  if(id===-1){
    let obj = {};
    obj[current] = [myData[index][current]];
    result.push(obj);
  // find, let push
  }else{
    result[id][current].push(myData[index][current]);
  }
});
console.log(result);

Comments

0

First use reduce function to create an object then loop over it & in new array push the value

var myData = [{
    123: 1
  },
  {
    123: 2
  },
  {
    124: 3
  },
  {
    124: 4
  }
];


let k = myData.reduce(function(acc, curr) {
  let getKey = Object.keys(curr)[0];// get the key
  let getVal = Object.values(curr)[0] //get the value
  //check if key like 123,124 exist in object
  if (!acc.hasOwnProperty(getKey)) { 
    acc[getKey] = [getVal]
  } else {
    acc[getKey].push(getVal)
  }
  return acc;

}, {})
let newArray = [];
for (let keys in k) {
  newArray.push({
    [keys]: k[keys]
  })
}
console.log(newArray)

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.