[英]Modifying an array of objects in JavaScript
我有這樣的對象數組
[ { '0': { notify_item: '1' } },
{ '1': { notify_item: '2' } },
{ '2': { notify_item: '3' } } ]
現在,我想用諸如'Invoice'
類'Invoice'
文本替換'0'
,並用諸如{ 'sms': true,email:'false' }
類的值替換該'0'
鍵的值。 我想將每個鍵替換為一些文本,並將其值替換為諸如{ 'sms': true,email:'false' }
所以更換后我想要這樣的東西
[ { 'Invoice': { 'sms': true,email:'false' } },
{ 'ManualReminder': { 'sms': true,email:'false' },
{ 'AutomaticReminder': { 'sms': true,email:'false' } ]
我無法理解我已經嘗試了拼接方法,但是它不起作用。 請給一些提示
可能不需要轉換數據,您可能只是獲得新結果。 也許這樣的事情會幫助您。
var input = [ { '0': { notify_item: '1' } }, { '1': { notify_item: '2' } }, { '2': { notify_item: '3' } } ]; var keyMap = {'0': 'Invoice', '1': 'ManualReminder', '2': 'AutomaticReminder'}; var result = Object.keys(input).map(function (key) { var item = {}, value = input[key]; //{notify_item:'1'} for first iteration //do your logic to convert {notify_item: '1' | '2' | '3'} item[keyMap[key]] = ''; //to whatever you need return item; }); console.log(result);
這是map
工作。
這也比應該做的要難,因為您的數據結構很奇怪。 像{ notification_type: 0, notify_item: 1 }
這樣的操作更容易嗎?
使用Array.map
函數遍歷數組。 在map
函數中,可以使用switch
語句來匹配適當的值並返回所需的輸出。
var arr = [{ '0': { notify_item: '1' } }, { '1': { notify_item: '2' } }, { '2': { notify_item: '3' } }]; var modifiedArr = arr.map(function(item) { var newItem = {}; for ( var key in item) { var newItemKey = getKey(key); var newItemValue = getValue(item[key]); } newItem[newItemKey] = newItemValue; return newItem; }); console.log(modifiedArr); function getKey (key) { switch(key) { case '0': return 'Invoice'; case '1': return 'ManualReminder'; case '2': return 'AutomaticReminder'; default: return 'default'; } } function getValue (value) { switch(value.notify_item) { case '1': return { 'sms': true,email:'false' }; case '2': return { 'sms': true,email:'false' }; case '3': return { 'sms': true,email:'false' }; default: return 'default'; } }
[ { 'Invoice': { 'sms': true,email:'false' } }, { 'ManualReminder': { 'sms': true,email:'false' }, { 'AutomaticReminder': { 'sms': true,email:'false' } ]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.