简体   繁体   English

react-native:如何正确格式化对象值

[英]react-native : How to format object value properly

I am trying to create an empty object . 我正在尝试创建一个空object First, each field will have a name with empty values. 首先,每个字段都有一个带有空值的名称。 Every thing works fine but I am having a trouble when formatting the name field 一切正常,但格式化name field时遇到麻烦

This is my code: 这是我的代码:

@observable member = {
//This name field doesn't work
    [{name:''}] :
    {
      age: '',
      email: '',
      job:'',
      info: [
        {
          email: '',    
          phone:'',
          address: ''
        }
      ],
    }
  }

When I console.log(member) I get this: 当我console.log(member)我得到这个:

[object Object]: {dots: "", selected: "", day: "", task: Array(1), name: ""}

Instead of [object Object] I want to get name:'' Is it possible to do this? 我想要代替[object Object] name:''可以这样做吗?

Objects are written as name : value pairs, your object doesn't have a proper key which is [{name: ''}] . 对象被写为name对,您的对象没有适当的键[{name: ''}] You can do the following to properly format your object. 您可以执行以下操作以正确格式化对象。

@observable member = {
 // will store names in array
 // or just do 
 // name: '',
 name: '',
 age: '',
 email: '',
 job:'',
 info: [
    {
      email: '',    
      phone:'',
      address: ''
      }
   ],
}

or 要么

@observable member = {
  names : [{'name': ''}],
  memberInfo: {
  age: '',
  email: '',
  job:'',
  info: [
    {
      email: '',    
      phone:'',
      address: ''
    }
  ],
  }
}

Then access the value, like 然后访问值,就像

// if it's the array
member.names[0].name
// or if it's not an array
member.name

You can convert Javascript object to JSON using JSON.Stringify(). 您可以使用JSON.Stringify()将Javascript对象转换为JSON。

console.log(JSON.Stringify(member).name)

Should do the job. 应该做的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM