i have an array of objects, looking like this:
[
{
"label": "anystring",
"processowner": ["any name"],
"withwhat": ["any text"],
"withwho": ["any text"],
"processstep": ["any text"],
"cluster": ["anyValue1"]
},
{
"label": "anystring",
"processowner": ["any name"],
"withwhat": ["any text"],
"withwho": ["any text"],
"processstep": ["any text"],
"cluster": ["anyValue2"]
},
{
"label": "anystring",
"processowner": ["any name"],
"withwhat": ["any text"],
"withwho": ["any text"],
"processstep": ["any text"],
"cluster": ["anyValue1"]
},
.........
]
The important Key, Value pair is "cluster". It is possible that there are more objects with the same '"cluster"'-Value. What i want is a new Array with just the "cluster"-Value. But each only once! That's were im struggling.
What i did so far is looping over the given array and compare the current "cluster"-Value with a second(final) array "tempNewJson" (second loop) - filled with the first object "initObj" of the given array in it. If the Value is already in "tempNewJson" i want the code to do nothing. If the Value is not yet in "tempNewJson" i want to add it. But i still get duplicates and a wrong number of Values in my final array "tempNewJson".
function convertJSON(initJson) {
var initObj = {};
initObj.title = initJson[0].cluster.toString();
initObj.scale = 6;
initObj.type = 'group-case-5-3';
initObj.children = [];
tempNewJson.push(initObj);
var contains = false;
// Schleife über alle Items in initialem JSON
for (var i = 0; i < initJson.length; i++) {
// Schleife über bisher hinzugefügte Objekte in tempNewJSON
contains = false;
for(var j = 0; j < tempNewJson.length; j++) {
contains = false;
if(initJson[i].cluster.toString() === tempNewJson[j].title) {
contains = true;
console.log(initJson[i].cluster.toString());
break;
}
}
if(contains === false) {
initObj.title = initJson[i].cluster.toString();
console.log('test: ' + initJson[i].cluster.toString());
tempNewJson.push(initObj);
}
}
}
Anyone knows how to fix this? Thanks.
The Output should look like this
["anyValue1", "anyValue2", .....]
I used Nina Scholz's answer like this:
var result = initJson.reduce(function (tempNewJson, initJson) {
!~tempNewJson.indexOf(initJson.cluster) && tempNewJson.push(initJson.cluster.toString());
return tempNewJson;
}, []);
console.log(result);
What i get know ist the following array:
['anyValue1', 'anyValue2', 'anyValue1', 'anyValue3', 'anyValue1', .........
]
But what i want is:
['anyValue1', 'anyValue2', 'anyValue3', 'anyValue4', 'anyValue5', .........
]
!~tempNewJson.indexOf(initJson.cluster) && tempNewJson.push(initJson.cluster.toString())this way, then you need atoString()also in theindexOfpart like!~tempNewJson.indexOf(initJson.cluster.toString()) && tempNewJson.push(initJson.cluster.toString())