简体   繁体   中英

How to get value of key in same node level with JSON format

I have this JSON format structure

  valuesColors : [{
    key: "<75%",
    color:"61C56E"
  },
  {
    key: ">=75%&<90%",
    color:"6144RF"
  },
  {
    key: ">90%",
    color:"333RTE"
  }
]

I would get for exemple valuesColors.color of valuesColor.key == ">75%". the problem here I have the value in the same level of the key so I can't use .

You can't use . because your object is an array type and each element in that array is a json node. So you'd need to access the relevant index and then you can operate on the object.

let array = [{key: '1'}, {key: '2'}];
let jsonNode = array[0];
console.log(jsonNode.key);
console.log(array[0].key);
console.log(array[1].key);
console.log(array.key); // Will not work as this is an array, not a json object.

Array.find() :

const result = valuesColors.find(entry => {
  return entry.key == "<75%"; // or what ever logic
});

console.log(result.color); // -> 61C56E

https://stackblitz.com/edit/how-to-get-value-of-key-in-same-node-level-with-json-format?file=index.js

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM