Javascript:遍历JSON对象 [英] Javascript: Iterating over JSON objects

查看:43
本文介绍了Javascript:遍历JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要迭代的JSON对象.

I have a JSON object that I want to iterate through.

"phone": {
    "Samsung": {
        "type": "S7"
    },
    "iPhone": {
        "type": "6S"
    },
    "Google": {
        "type": "Pixel"
    }
}

我正在使用 Object.key 映射所有这些值,我认为这是使用对象的正确方法:

I'm using Object.key to map through each of these values, which I THINK is the correct way to work with objects:

render() {
    //this.props.phone contains the objects "Samsung", "iPhone", and "Google"
    return (
        Object.keys(this.props.phones).map((type) => {
            console.log(type)
            return (
                <p>Type of phone: {type}</p>
            )
        })
    )
} 

但是,当我期望对象返回时,上面的 console.log 会返回此值:

However, the console.log above returns this when I was expecting an object to return:

为什么它返回一个值,而不是一个对象?

Why is it returning a value, and not an object?

推荐答案

严格来说,这是答案,但是可以很容易地将其填充到旧版Javascript中.

This is strictly speaking a ecmascript-2017 answer, but it can easily be shimmed into older versions of Javascript.

您要使用 Object.值 Object.entries 遍历对象中的所有属性.其中 Object.keys 为您提供键, Object.values 为您提供属性(嗯,嗯),而 Object.entries 为您提供数组对象中每个条目的 [键,值] .

You want to use either Object.values or Object.entries to loop through all the properties in an object. Where Object.keys gives you the keys, Object.values gives you the properties (well, duh) and Object.entries gives you an array [key, value] for each entry in the object.

您没有在当前代码中使用密钥,因此这是 Object.values 选项:

You don't use the key in your current code, so here's the Object.values option:

    Object.values(this.props.phones).map((type) => {
        console.log(type)
        return (
            <p>Type of phone: {type}</p>
        )
    })

,如果您想同时使用这两个选项,则这里是 Object.entries 选项:

and here's the Object.entries option, if you wanted to use both:

    Object.entries(this.props.phones).map(([make, type]) => {
        console.log(make)
        console.log(type)
        return (
            <p>Make of phone: {make}</p>
            <p>Type of phone: {type}</p>
        )
    })

您会看到我们正在使用ES6解构从我们从 Object.entries 获得的数组中获取两个值.

You'll see that we're using ES6 destructuring to get the two values out of the array we get from Object.entries.

垫片在每个功能的MDN页面上链接.

The shims are linked on the MDN pages for each function.

这篇关于Javascript:遍历JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆