获取对象值,不使用Object.values()

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

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 =&gt; object[key]);
}

console.log(values(&#39;{&quot;foo&quot;:&quot;bar&quot;,&quot;baz&quot;:42}&#39;));

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 02:32:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75439913.html
匿名

发表评论

匿名网友

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

确定