2017-05-30 25 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; }