2017-05-30 23 views
-2

我已经JSON object格式化为JSON对象转化

{ 
    id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435', 
    contactData: { 
     phone: '526 669 77', 
     email: '[email protected]', 
     skype: 'skype', 
     company_name: 'CLIent22', 
     address: 'address', 
     contact_person: 'Person' 
    } 
} 

我想把它改造成

{ 
     id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435', 
     phone: '526 669 77', 
     email: '[email protected]', 
     skype: 'skype', 
     company_name: 'CLIent22', 
     address: 'address', 
     contact_person: 'Person' 
    } 

如何它可以做。寻找你的帮助和建议。

+0

是罚款,发生变异原来的对象? –

+0

这不是有效的JSON。 – Quentin

回答

1

什么

var yourobject ={ 
    id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435', 
    contactData: { 
     phone: '526 669 77', 
     email: '[email protected]', 
     skype: 'skype', 
     company_name: 'CLIent22', 
     address: 'address', 
     contact_person: 'Person' 
    } 
} 
var newObject=yourobject.contactData; 
newObject.id=yourobject.id; 
+0

谢谢你,你的回答对我来说是最好的 – vladja

+0

很高兴帮助,请不要忘记标记为已回答 – jitender

3
在ES6

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

或使用jQuery:

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

我没有使用jQuery,不幸的是我不能使用ES6语法,但你的答案看起来不错,但在我的情况下不是这样 – vladja

+0

我猜@jitender的答案会很好。 – philipp

0

你可以使用Object.create用于生成对象的副本,没有突变原目的。然后添加其他属性。

var original = { id: 'a60c09fa-9b60-4b14-9ee6-41d64d243435', contactData: { phone: '526 669 77', email: '[email protected]', 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; }