Javascript:遍历 JSON 对象

IT技术 javascript reactjs ecmascript-6
2021-04-27 16:42:07

我有一个要遍历的 JSON 对象。

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

我正在使用Object.key这些值中的每一个进行映射,我认为这是处理对象的正确方法:

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当我期待一个对象返回时上面会返回这个:

在此处输入图片说明

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

4个回答

这严格来说是一个 答案,但它可以很容易地填充到旧版本的 Javascript 中。

您想使用Object.valuesObject.entries循环遍历对象中的所有属性。WhereObject.keys为您提供键,Object.values为您提供属性(好吧,废话)并Object.entries[key, value]对象中的每个条目提供一个数组

您没有在当前代码中使用密钥,所以这里有一个Object.values选项:

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

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

    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

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

因为您迭代对象键。要在您的情况下返回对象,您必须使用给定的键来获取其值:

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

}

对象的键是字符串,因此当您查看Object.keys(someObject). 与该键关联的值是您要查找的对象。为了获得该值,在您的地图迭代中,您需要使用您的键访问该对象。

var self = this;//close over this value for use in map
return (
    Object.keys(this.props.phones).map((type) => {
        console.log(self.props.phones[type]);//this will yield the object
        return (
            <p>Type of phone: {self.props.phones[type]}</p>
        )
    })
)

您已经迭代了这些键。因此,type循环中变量将设置为Samsung,iPhoneGoogle然后您使用它this.props.phone[type]来访问值对象。请修复phones您的代码phone中与 JSON 对象中的键不同的键。

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