2016-05-17 4 views
1

Мой объект JSON как это:Как преобразовать один объект json в объект массива json?

var a = [{ 
    "attributes": { 
     "Code": "SGL", 
     "Total": "811400" 
    }, 
    "DayPrice": { 
     "Date": "2016-07-22", 
     "Rate": "811400" 
    } 
}]; 

Я хочу изменить DayPrice в массив как это:

var a = [{ 
    "attributes": { 
     "Code": "SGL", 
     "Total": "811400" 
    }, 
    "DayPrice": [{ 
     "Date": "2016-07-22", 
     "Rate": "811400" 
    }] 
}]; 

Любое решение, чтобы решить мою проблему?

Большое спасибо

ответ

2

Вы должны были бы перебрать массив объектов и обернуть DayPrice свойство каждого массива, например:

for (var i = 0; i < a.length; i++) { 
    a[i].DayPrice = [a[i].DayPrice]; 
} 

Working example

+0

Мне нужна помощь. Смотрите здесь: http://stackoverflow.com/questions/39652796/why-multiple-datepicker-not-working/39652870#39652870 –

2

Присвоить массив со свойством в собственность.

a[1].DayPrice = [a[1].DayPrice]; 

Или использовать цикл:

var a = [{ "attributes": { "Code": "SGL", "Total": "811400" }, "DayPrice": { "Date": "2016-07-22", "Rate": "811400" } }]; 
 

 
a.forEach(function (a) { 
 
    if ('DayPrice' in a) { 
 
     a.DayPrice = [a.DayPrice]; 
 
    } 
 
}); 
 

 
document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>');

+0

я нужна помощь. Смотрите здесь: http://stackoverflow.com/questions/39652796/why-multiple-datepicker-not-working/39652870#39652870 –

0

Надеется, что это поможет

var a = [{ 
      "attributes": { 
       "Code": "SGL", 
       "Total": "811400" 
      }, 
      "DayPrice": { 
       "Date": "2016-07-22", 
       "Rate": "811400" 
      } 
     }]; 

var _getDayPrice = a[0].DayPrice; 

var _dayPriceArray = []; 
_dayPriceArray.push({ 
    "Date":_getDayPrice.Date, 
    "Rate":_getDayPrice.Rate 
}) 
a[0].DayPrice=_dayPriceArray; 
console.log(a); 

Проверить это jsFiddle

+0

Мне нужна помощь. Посмотрите здесь: http://stackoverflow.com/questions/39652796/why-multiple-datepicker-not-working/39652870#39652870 –

Смежные вопросы