从字符串路径获取 JSON 值

huangapple go评论71阅读模式
英文:

Get JSON value from string path

问题

我需要从我的变量中提取JSON值。
例如,我有这个JSON:

const myJson = {
  "id": "someID",
  "organizations": [
    "0": {
      "id": "organizationId",
      "name": "organizationName"
    },
    "1": {
      ...
    },
    ...
  ] 
}

和这个变量:

var pathOfKey = ["organizations","0","id"];

如何从我的变量'pathOfKey'中获取'organizationId'的值?

我事先不知道我的键的路径是什么,但我有一个包含这些信息的变量。
我需要获取数组中所有组织的ID。

英文:

I need to extract a JSON value starting from my variable.
for example i have this json

const myJson = {
  "id": "someID",
  "organizations": [
    "0": {
      "id": "organizationId",
      "name": "organizationName"
    },
    "1": {
      ...
    },
    ...
  ] 
}

and this variable

var pathOfKey = ["organizations","0","id"];

how to get the value of 'organizationId' from my variable 'pathOfKey'?

I don't know in advance what the path to my key is but I have a variable with this information.
I need to get all the organization IDs of my array.

答案1

得分: 1

let obj = {
  "a": { "b": "value" }
}

let tmpObj = obj;
let arr = ["a", "b"];

arr.forEach((objKey) => {
  if (tmpObj[objKey] !== undefined) {
    tmpObj = tmpObj[objKey];
  }
});

console.log(tmpObj);

类似这样的代码可以完成任务。也可以使用递归函数来完成。

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let obj = {
&quot;a&quot;: {&quot;b&quot;: &quot;value&quot;}
}

let tmpObj = obj;
let arr = [&quot;a&quot;, &quot;b&quot;];

arr.forEach((objKey) =&gt; {
  if (tmpObj[objKey] !== undefined) {
  	tmpObj = tmpObj[objKey];
  }
});

console.log(tmpObj);

<!-- end snippet -->

Something like this will do the job.
Also, it can be done with a recursion function

答案2

得分: 0

基本上,您需要迭代pathOfKey数组,并同时遍历数组中的键以访问对象。

function getValueFromObject(obj, path) {
  let currentNode = obj;

  for (key of path) {
    if (!currentNode.hasOwnProperty(key)) {
      return null;
    }
    currentNode = currentNode[key];
  }
  
  return currentNode;
}

getValueFromObject(myJson, pathOfKey)
英文:

Basically you need to iterate pathOfKey array and traverse the object with key in the array simultaneously.

function getValueFromObject(obj, path) {
  let currentNode = obj;

  for (key of path) {
    if (!currentNode.hasOwnProperty(key)) {
      return null;
    }
    currentNode = currentNode[key];
  }
  
  return currentNode;
}

getValueFromObject(myJson, pathOfKey)

答案3

得分: 0

The easiest solution is probably to use reduce().

const value = pathOfKey.reduce((item, key) => item[key], myJson);
英文:

The easiest solution is probably to use reduce().

const value = pathOfKey.reduce((item, key) =&gt; item[key], myJson);

huangapple
  • 本文由 发表于 2023年3月15日 19:12:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743928.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定