1

Say I have an array of objects

var result = [{
    "sss": "sssssss",
    "yyy": "ssdsdsds",
    "www": "1212121",
    "Group": "Mango"
}, {
    "sss": "sssssss",
    "yyy": "ssdsdsds",
    "www": "1212121",
    "Group": "Mango"
}]

I want a final result like :

var result ={
   "Mango" : [
        {
            "sss": "sssssss",
            "yyy": "ssdsdsds",
            "www": "1212121"
        }, {
            "sss": "sssssss",
            "yyy": "ssdsdsds",
            "www": "1212121"
        }
    ]
}

So I did this

var obj = [];

for(var i = 0; i < result.length; i++ ){
    if(obj[result[i].Group] && obj[result[i].Group].constructor === Array ){

    }else{
        obj[result[i].Group] = [];
        // ################### PROBLEM ==========
        var x = result[i];
        delete x.Group;
        console.log(result[i]);
        // ################### ==================
        obj[result[i].Group].push(result[i]); // error: result[i].Group is undefined 
    }
}

the code "delete x.Group" should delete property "Group" from var "x" But actually the console.log(result[i]); shows the property "Group" is deleted from result[i] (which is original). HOW?

Looks like variable x is reference to the original result[i], this am not sure. How the deleting a property from the copy of the object is affecting the original. How to overcome this issue?

Siddhartha Chowdhury
  • 2,724
  • 1
  • 28
  • 46
  • 2
    You answered it yourself `Looks like variable x is reference to the original result[i]` – Waleed Iqbal Jan 23 '18 at 07:37
  • 1
    See my answer to this question for some details about @WaleedIqbal's comment: [Copy a variable's value into another](https://stackoverflow.com/questions/18829099/copy-a-variables-value-into-another/29096222) – Michael Geary Jan 23 '18 at 07:44
  • If you want to copy a JavaScript array instead of just getting a new reference to it, you can use the `.slice()` method, e.g. `var x = result[i].slice();` Note that this does a "shallow" copy; it makes a new array, but it doesn't make new copies of any nested objects, only references to them. Other options such as a "deep" copy are mentioned in the answer I linked above. – Michael Geary Jan 23 '18 at 07:46

1 Answers1

1

You just need to use a hash structure. Also. use delete operator in order to delete one object' property.

var result = [{
    "sss": "sssssss",
    "yyy": "ssdsdsds",
    "www": "1212121",
    "Group": "Mango"
}, {
    "sss": "sssssss",
    "yyy": "ssdsdsds",
    "www": "1212121",
    "Group": "Mango"
}]

var groupByField = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    delete x[key];
    return rv;
  }, {});
};
console.log(groupByField(result, 'Group'));

However,

How the deleting a property from the copy of the object is affecting the original ?

You have to apply deep clone for that object.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128