Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
15
rated 0 times [  16] [ 1]  / answers: 1 / hits: 80706  / 11 Years ago, fri, september 20, 2013, 12:00:00

I'm trying to take some data from an existing object and group it into a new one. The problem I am having is checking if the object key exists so I can either create a new one, or append data to an existing one.



I've found a few similar questions but none of the answers worked so I'm a bit stuck. It always ends up finding it doesn't exist and creating duplicate keys.



I have the following code, where xxx is where I need to check if the key exists:



var groups = [];    

for (var i=0; i<something.length; i++) {

var group_key = 'group_'+something[i].group_id;

if (xxx) {

// New group

var group_details = {};

group_details[group_key] = {
group_name: something[i].group_name,
items: [
{ 'name': something[i].name }
]
};
groups.push(group_details);

} else {

// Existing group

groups[group_key].items.push({
'name': something[i].name
});

}

}


The something I am passing in, is pretty simple, basically in the form of:



[
{
group_id: 3,
group_name: 'Group 3',
name: 'Cat'
},
{
group_id: 3,
group_name: 'Group 3',
name: 'Horse'
},
{
group_id: 5,
group_name: 'Group 5',
name: 'Orange'
}
]

More From » json

 Answers
11

The best way to achieve this would be to rely on the fact that the in operator returns a boolean value that indicates if the key is present in the object.



var o = {k: 0};

console.log('k' in o); //true


But this isin't your only issue, you do not have any lookup object that allows you to check if the key is already present or not. Instead of using an array, use a plain object.



var groups = {};


Then instead of groups.push(...), do groups[group_key] = group_details;



Then you can check if the group exist by doing if (group_key in groups) {}


[#75558] Thursday, September 19, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeremiahianx

Total Points: 629
Total Questions: 106
Total Answers: 112

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
;