javascript - Searching JSON value multiple levels deep -
i have following data object, , there more similar ones within entities
:
function loadcardlibrary() { var cardlibrary = { entities: [ { name: "spareparts", values: { sickness: 0, attack: 0, scrap: 3, manacost: 0 }, apply: [ applycreature("mech"), applyhealth(1), applynoattack(true) ] } ] }; return cardlibrary; }
i trying write function (see example) search name
value, go in object , search check specific apply
value, so:
function checkhasnoattack(entityname) { (var entity in cardlibrary.entities) { if (cardlibrary.entities[entity].name === entityname) { // debugging console.log(cardlibrary.entities[entity]); console.log(); // blank line (var applied in cardlibrary.entities[entity].apply) { if (cardlibrary.entities[entity].apply[applied].applynoattack === true) { console.log(entityname + " cannot attack."); } else { console.log("test"); break; } } } } }
when call right after, this:
var canitattack = checkhasnoattack("spareparts");
...this result:
{ name: 'spareparts', values: { sickness: 0, attack: 0, scrap: 3, manacost: 0 }, apply: [ 'mech', 1, true ] } test
instead of test
comes else
, trying log respond first if
statement, , log:
spareparts cannot attack.
with understanding more complicated logic replace console.log
there need work, have been tinkering , can't seem right. appreciated!
this pretty simple:
function check(a) { var result = null; cardlibrary.entities.foreach(function(b){ if (b.name === a) { if (b.apply[2] === true) { console.log(a + " cannot attack!"); } else { console.log("test"); } result = b; } }); return result; }
apply
array, have use [2]
select value
arrays ugly job @ this, recommend modifying apply
object like:
apply: { creature: applycreature("mech"), health: applyhealth(1), noattack: applynoattack(true) }
then can use code:
function check(a) { var result = null; cardlibrary.entities.foreach(function(b){ if (b.name === a) { if (b.apply.noattack === true) { console.log(a + " cannot attack!"); } else { console.log("test"); } result = b; } }); return result; }
Comments
Post a Comment