我如何使用JavaScript编辑JSON中的属性

How can I edit the attributes in a JSON using JavaScript

本文关键字:属性 JSON 编辑 何使用 JavaScript      更新时间:2023-09-26

我有以下JSON:

[{ ID: '0001591',
    name: 'EDUARDO DE BARROS THOMÉ',
    class: 'EM1A',
    'phone Pai': '(11) 999822922',
    'email Pai': 'sergio7070@globo.com',
  { ID: '0001592',
    name: 'JEAN LUC EUGENE VINSON',
    class: 'EM1A',
    'phone Pai': '(11) 981730534',
    'email Pai': 'jeanpevinson@distock.com.br',

我希望它看起来像这样:

[{ ID: '0001591',
    name: 'EDUARDO DE BARROS THOMÉ',
    class: 'EM1A',
    Address[
        type:Phone,
        tag:Pai,
        address:'(11) 999822922',
]
Address[
        type:Email,
        tag:Pai,
        address:'sergio7070@globo.com',
]
 },
  { ID: '0001592',
    name: 'JEAN LUC EUGENE VINSON',
    class: 'EM1A',
Address[
        type:Phone,
        tag:Pai,
        address:'(11) 981730534',
]
Address[
        type:email,
        tag:Pai,
        address:'jeanpevinson@distock.com.br',
]
     } ]
你有什么建议吗?

修复JSON后,假设您有这个JS对象(顺便说一下)。它仍然是一个无效的JSON,但一个有效的JS对象):

var json = [{ ID: '0001591',
    name: 'EDUARDO DE BARROS THOMÉ',
    class: 'EM1A',
    'phone Pai': '(11) 999822922',
    'email Pai': 'sergio7070@globo.com'
  },
  { ID: '0001592',
    name: 'JEAN LUC EUGENE VINSON',
    class: 'EM1A',
    'phone Pai': '(11) 981730534',
    'email Pai': 'jeanpevinson@distock.com.br'
   }];

这是一个双元素数组,每个数组元素都是一个对象,所以要访问每个对象,需要使用索引,例如:

json[0];
json[1];

要访问对象的特定属性,需要使用键,例如:

json[0].name;
json[0]['name']; // equal to above, but you'll need it for your keys with spaces

最后添加一个对象属性,我们可以这样做:

json[0].Address = []; // make it an empty array
json[0].Address.push({
    type: 'Phone',
    tag: 'Pai',
    address: '(11) 999822922'}); // push the phone number
json[0].Address.push({
    type: 'Email',
    tag: 'Pai',
    address: 'sergio7070@globo.com'}); // push the email

这将为您提供您所要求的最终对象。

如果您希望使其自动(我看到您正在读取'phone Pai''email Pai'值来构建这些新对象),您需要循环整个数组,解析对象键以找出类型和标记,最后根据解析的数据为每个对象添加对象属性。