Javascript: Iterating over JSON objects
我有一个JSON对象要迭代。
1 2 3 4 5 6 7 8 9 10 11  | "phone": { "Samsung": { "type":"S7" }, "iPhone": { "type":"6S" }, "Google": { "type":"Pixel" } }  | 
我正在使用
1 2 3 4 5 6 7 8 9 10 11 12 13  | 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> ) }) ) }  | 
但是,当我期望一个对象返回时,上面的

为什么它返回一个值,而不是一个对象?
严格来说,这是一个ECMAScript-2017答案,但它可以很容易地填充到旧版本的JavaScript中。
您希望使用
您在当前代码中不使用密钥,所以这里是
1 2 3 4 5 6 7 8  |     Object.values(this.props.phones).map((type) => { console.log(type) return ( <p> Type of phone: {type} </p> ) })  | 
这里是
1 2 3 4 5 6 7 8 9 10 11 12  |     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析构函数从我们从
每个功能的MDN页面上都链接了垫片。
因为您迭代对象键。如果要返回对象,则必须使用给定的键来获取其值:
1 2 3 4 5 6 7 8 9 10  | 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]) ... }) ) }  | 
对象的键是字符串,所以当您查看
1 2 3 4 5 6 7 8 9 10 11  | 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> ) }) )  | 
您可以使用arrow函数和参数的析构函数来简化代码的读取。由于
1 2 3 4 5 6 7 8 9  | const {phones} = this.props; const phoneKeys = Object.keys(phones); render() { return ( phoneKeys.map(phoneKey) => <p key={phoneKey}>Type of phone: {phones[phoneKey].type} </p>) ) }  | 
您已经迭代了这些键。所以循环中的
1 2 3 4 5 6 7 8 9 10 11 12 13  | 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> ) }) ) }  |