简体   繁体   English

从 JSON 嵌套 object 键中获取值

[英]Get value from JSON nested object key

I'm trying to write a function gets a key ( string ) and returns values of it if it exists in the JSON.我正在尝试编写一个 function 获取一个键(字符串)并返回它的值,如果它存在于 JSON 中。

Received JSON:收到 JSON:

[
  {
    "some_key1": [
      {"key": "value1"},
      {"key": "value2"},
      {"key": "value3"}
    ]
  },
  {
    "some_key2": [
      {"key": "value4"},
      {"key": "value5"},
      {"key": "value6"}
    ]
  },
  {
    "default_val": [
      {"key": "value7"},
      {"key": "value8"},
      {"key": "value9"}
    ]
  }
]

The structure looks like this and the only thing that might vary is the number of inner objects.结构看起来像这样,唯一可能不同的是内部对象的数量。

Function that would return the array : Function 将返回数组

interface InnerObject {
    key: string;
}

const getValues = (key = "default_val"): InnerObject[] => {
    /* working code */
}

Example expected output:预期的示例 output:

> getValues("some_key2");
[{"key": "value4"},{"key": "value5"},{"key": "value6"}]
> getValues();
[{"key": "value7"},{"key": "value8"},{"key": "value9"}]

Any elegant solutions?任何优雅的解决方案?

Same solution as Nick, but with find to return object directly:与 Nick 相同的解决方案,但使用find直接返回 object:

 const data = [ { "some_key1": [ {"key": "value1"}, {"key": "value2"}, {"key": "value3"} ] }, { "some_key2": [ {"key": "value4"}, {"key": "value5"}, {"key": "value6"} ] }, { "default_val": [ {"key": "value7"}, {"key": "value8"}, {"key": "value9"} ] } ]; const getValues = (key = 'default_val') => data.find(o => Object.keys(o)[0] == key); console.log(getValues('some_key2')); console.log(getValues());

You could use Array.filter with a test that the key of the object is the same as the passed parameter (or default_val if one is not passed):您可以使用Array.filter来测试 object 的键是否与传递的参数相同(如果未传递,则为default_val ):

 const data = [ { "some_key1": [ {"key": "value1"}, {"key": "value2"}, {"key": "value3"} ] }, { "some_key2": [ {"key": "value4"}, {"key": "value5"}, {"key": "value6"} ] }, { "default_val": [ {"key": "value7"}, {"key": "value8"}, {"key": "value9"} ] } ]; const getValues = (key = 'default_val') => data.filter(o => Object.keys(o)[0] == key); console.log(getValues('some_key2')); console.log(getValues());

This code will return multiple values if there is more than one value with the same search key.如果有多个值具有相同的搜索键,此代码将返回多个值。 If not, it's more efficient to use Array.find as described in some of the other answers.如果不是,则使用Array.find更有效,如其他一些答案中所述。

That structure is not ideal for searching.这种结构不适合搜索。 Why not convert it to a better structure first, and use that for the searching?为什么不先将其转换为更好的结构,然后将其用于搜索?

Something like this might do:这样的事情可能会做:

 const makeSearcher = (input, obj = Object.assign (...input)) => (key) => obj [key] || obj.default_val const input = [{some_key1: [{key: "value1"}, {key: "value2"}, {key: "value3"}]}, {some_key2: [{key: "value4"}, {key: "value5"}, {key: "value6"}]}, {default_val: [{key: "value7"}, {key: "value8"}, {key: "value9"}]}] const search = makeSearcher (input) console.log (search ('some_key2')) console.log (search ())

This assumes there is only one object with a given key.这假设只有一个 object 具有给定的密钥。 If not, I would look to Nick's solution.如果没有,我会考虑尼克的解决方案。

While this is an O (1) search function, no logical answer to this is likely to be more than O (n) , so I don't really think performance is likely to be a big issue either way.虽然这是一个O (1)搜索 function,但对此的逻辑答案可能不会超过O (n) ,所以我真的不认为性能可能是一个大问题。

This will do:这将做:

const getValues = (key = "default_val"): InnerObject[] => {
  return data.find(item => item[key])[key];
};

Here is a more generic solution using object-scan这是使用对象扫描的更通用的解决方案

The main advantage is that it's very easy to target eg deeper keys and multiple keys.主要优点是它很容易定位,例如更深的键和多个键。

 // const objectScan = require('object-scan'); const myData = [{ some_key1: [{ key: 'value1' }, { key: 'value2' }, { key: 'value3' }] }, { some_key2: [{ key: 'value4' }, { key: 'value5' }, { key: 'value6' }] }, { default_val: [{ key: 'value7' }, { key: 'value8' }, { key: 'value9' }] }]; const find = (data, key) => objectScan([key], { reverse: false, rtn: 'value' })(data) console.log(find(myData, '[*].some_key2[*]')); // => [ { key: 'value4' }, { key: 'value5' }, { key: 'value6' } ]
 .as-console-wrapper {max-height: 100%;important: top: 0}
 <script src="https://bundle.run/object-scan@13.8.0"></script>

Disclaimer : I'm the author of object-scan免责声明:我是对象扫描的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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