英文:
Get object values without using Object.values()
问题
我刚刚开始学习编程,正在解决这个挑战。在网上找不到相关的指导,提前感谢。
function keys(json) {
var obj = JSON.parse(json);
let result = [];
for (const key in obj) {
result.push(key);
}
return result;
}
我已经让它可以返回键,而没有使用 Object.keys,我有点假定可以简单地将 'key' 替换为 'value',但那不起作用。
function keys(json) {
var obj = JSON.parse(json);
var values = Object.keys(obj).map((key,value)=>{ values.push(value) });
return values;
}
我还尝试了这个,但我还不太了解 map 函数。
英文:
I just started learning to code and am working on this challenge. Having issues finding any relevant guidance online. Thanks in advance.
function keys(json) {
var obj = JSON.parse(json);
let result = [];
for (const key in obj) {
result.push(key);
}
return result;
}
I got this to work for returning keys without using Object.keys and I sort of assumed I could just swap the 'key' for 'value' but that didn't work.
function keys(json) {
var obj = JSON.parse(json);
var values = Object.keys(obj).map((key,value)=>{ values.push(value) });
return values;
}
Also tried this, but I don't really understand the map function yet.
答案1
得分: 1
这是你在寻找的内容吗?
英文:
Is this what you are looking for?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const obj = {a:3, b:4}
const result = []
for (const key in obj) {
result.push(obj[key])
}
console.log(result)
<!-- end snippet -->
答案2
得分: 0
使用Object.keys
可以获取数组的键(自有的、可枚举的)。要映射值,你需要使用属性访问器 与对象和键一起。
function values(json) {
const object = JSON.parse(json);
return Object
.keys(object)
.map(key => object[key]);
}
console.log(values('{ "foo": "bar", "baz": 42 }'));
此代码段使用Object.keys
获取了JSON对象的所有键,并使用map
方法映射这些键对应的值。然后,将结果打印到控制台。
英文:
With Object.keys
you get an array of keys (own, enummerable) of the array. for mapping values, you need to take a property accessor with object and key.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function values(json) {
const object = JSON.parse(json);
return Object
.keys(object)
.map(key => object[key]);
}
console.log(values('{"foo":"bar","baz":42}'));
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论