英文:
How can i access into an json without know the key?
问题
我有一个 JSON,内容如下:它们是错误,我需要打印出发生的错误,包括 error1、error2 或 error3 等等。
errors = {
"deployer": ["error1"],
"discard": ["error2"],
"worker": ["error3"]
// ...
}
有时只会出现 deployer
、discard
、worker
中的一个,或者全部或其中两个,但我不知道会发生什么样的错误。
英文:
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);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论