JSON对象转换

时间:2017-05-30 10:33:37

标签: javascript json object

我将JSON object格式化为

{ 
   id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435',
   contactData: {
      phone: '526 669 77',
      email: 'client@test.ee',
      skype: 'skype',
      company_name: 'CLIent22',
      address: 'address',
      contact_person: 'Person'
   }
}

我想将其转换为

{ 
       id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435',
       phone: '526 669 77',
       email: 'client@test.ee',
       skype: 'skype',
       company_name: 'CLIent22',
       address: 'address',
       contact_person: 'Person'
    }

如何做到这一点。寻找你的帮助和建议。

3 个答案:

答案 0 :(得分:3)

ES6中的

let result = {
  id: input.id,
  ...input.contactData
}

或使用jQuery:

var result = $.extend({ id: input.id }, input.contactData);

答案 1 :(得分:1)

怎么样?
var yourobject ={ 
   id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435',
   contactData: {
      phone: '526 669 77',
      email: 'client@test.ee',
      skype: 'skype',
      company_name: 'CLIent22',
      address: 'address',
      contact_person: 'Person'
   }
}
var newObject=yourobject.contactData;
newObject.id=yourobject.id;

答案 2 :(得分:0)

您可以使用Object.create生成对象的副本,而不会改变原始对象。然后添加其他属性。

var original = { id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435', contactData: { phone: '526 669 77', email: 'client@test.ee', skype: 'skype', company_name: 'CLIent22', address: 'address', contact_person: 'Person' } },
    result = Object.create(original.contactData);

result.id = original.id;
console.log(result);
console.log(original);
.as-console-wrapper { max-height: 100% !important; top: 0; }