DeeTee DeeTee - 2 months ago 7
JSON Question

Javascript populate array based on JSON object

I have a JSON object as follows:

var testJSON = [
{ "AssetA": "asset_a", "AssetB": "asset_b" },
{ "AssetA": "asset_a", "AssetB": "asset_b" },
{ "AssetA": "asset_c", "AssetB": "asset_d" },
{ "AssetA": "asset_c", "AssetB": "asset_e" }];


What I want to do is step through the object and add repeating keys to another array, usedAssets. Here is my code so far:

var usedAssets = [];

for (var key in testJSON) {
console.log("Current key: " + key + " " + "value: : " + testJSON[key].AssetA);
console.log("Current key: " + key + " " + "value: : " + testJSON[key].AssetB);

// check if in array
if ((isInArray(testJSON[key].AssetA, usedAssets) || isInArray(testJSON[key].AssetB, usedAssets))) {
break;
}
else {
usedAssets.push(testJSON[key].AssetA);
usedAssets.push(testJSON[key].AssetB);
}
}
console.log(usedAssets);



function isInArray(value, array) {
return array.indexOf(value) > -1;
}


However, my output of that is just an array with asset_a and asset_b. The usedAssets array should contain asset_a, asset_b, and asset_c. My end goal is to be able to determine at the end of the iteration, that I used asset_a only once, asset_b only once, and asset_c only once.

Answer

Basically, you could iterate all elements of the array and all properties of the object and count the occurence.

var testJSON = [{ "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_c", "AssetB": "asset_d" }, { "AssetA": "asset_c", "AssetB": "asset_e" }],
    count = {};

testJSON.forEach(o => Object.keys(o).forEach(k => count[o[k]] = (count[o[k]] || 0) + 1));

console.log(count);
console.log(Object.keys(count).filter(k => count[k] > 1));
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES5

var testJSON = [{ "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_a", "AssetB": "asset_b" }, { "AssetA": "asset_c", "AssetB": "asset_d" }, { "AssetA": "asset_c", "AssetB": "asset_e" }],
    count = {};

testJSON.forEach(function (o) {
    Object.keys(o).forEach(function (k) {
        count[o[k]] = (count[o[k]] || 0) + 1;
    });
});

console.log(count);
console.log(Object.keys(count).filter(function (k) {
    return count[k] > 1;
}));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments