如何在不知道键的情况下访问 JSON?

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

How can i access into an json without know the key?

问题

我有一个 JSON,内容如下:它们是错误,我需要打印出发生的错误,包括 error1、error2 或 error3 等等。

errors = {
  "deployer": ["error1"],
  "discard": ["error2"],
  "worker": ["error3"]
  // ...
}

有时只会出现 deployerdiscardworker 中的一个,或者全部或其中两个,但我不知道会发生什么样的错误。

英文:

I have a JSON like this: they are errors I need to print the error what happened error1, or error2 or error3 and so on

errors = {deployer: ['error1'],
 discard: ['error2'],
 worker: ['error3']
...}

sometimes they are only deployer or only discard or only worker or all or two of them, but I don't know what kind of error is going to happen.

答案1

得分: 0

这将通过errors对象的键进行映射,并记录每个键对应的值(如果不是空数组):

const errors = {
  deployer: ['error1'],
  discard: ['error2'],
  worker: ['error3']
  // ...
};

for (const key in errors) {
  if (errors[key].length > 0) {
    console.log(`${key}: ${errors[key]}`);
  }
}

你可以使用${errors[key].join(', ')}来将数组中的所有值连接起来,如果它们都是字符串。

英文:

This will map through the erros object keys and log the corresponding value for each key if it is not an empty array:

const errors = {
  deployer: ['error1'],
  discard: ['error2'],
  worker: ['error3']
  // ...
};

for (const key in errors) {
  if (errors[key].length > 0) {
    console.log(`${key}: ${errors[key]}`);
  }
}

you can use ${errors[key].join(', ')} to join all the values inside the array if they are all string

答案2

得分: 0

你可以使用Object.values()来获取对象的所有值,而不需要知道键。然后,对于这些值中的每个数组,你可以使用展开运算符来打印每个错误数组的所有元素。

const errors = {
    deployer: ['error1'],
    discard: ['error2'],
    worker: ['error3']
};

Object.values(errors).forEach((e) => {
    console.log(...e);
});
英文:

You can use Object.values() to get all the values of the object without knowing the keys. Then, for each array in those values, you can use the spread operator to print all elements of each error array.

const errors = {
    deployer: ['error1'],
    discard: ['error2'],
    worker: ['error3']
};

Object.values(errors).forEach((e) => {
	console.log(...e);
});

huangapple
  • 本文由 发表于 2023年7月7日 07:11:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76633029.html
  • javascript

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

确定