Javascript populate array based on JSON object -
i have json object 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 want step through object , add repeating keys array, usedassets. here code far:
var usedassets = []; (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, output of array asset_a , asset_b. usedassets array should contain asset_a, asset_b, , asset_c. end goal able determine @ end of iteration, used asset_a once, asset_b once, , asset_c once.
basically, iterate elements of array , properties of object , count 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
Post a Comment