Java Script + JSON解析並轉換為Array

[英]Java Script + JSON Parsing and converting into Array


I'm looking for help in converting a particular elements in JSON message to an array using java script at run time. We wanted the script to be more generic. Actually we were trying the following which worked for single element and while changing it to handle for multiple elements at run time its not working.

我正在尋找幫助在運行時使用java腳本將JSON消息中的特定元素轉換為數組。我們希望腳本更通用。實際上我們正在嘗試以下哪個適用於單個元素,並且在更改它以在運行時處理多個元素時它不起作用。

//Working for Single element - Static 

var bodyContext = JSON.parse(response.content)
if(bodyContext.companylist.company.constructor !== Array){
    bodyContext.companylist.company = [bodyContext.companylist.company]
}

The above code works and converts Company in JSON message as a Array, Where as the below we tried for multiple elements is not working

上面的代碼工作並將JSON消息中的Company轉換為數組,其中下面我們嘗試多個元素不起作用

//Not Working for multiple elements - dynamic

var bodyContext = JSON.parse(response.content)

var elementName = "";
//Loop runs every time and changes the value of elementName at every iteration

if(bodyContext.elementName .constructor !== Array){ //not working    

    bodyContext.elementName  = [bodyContext.elementName] //Not working
}

instead of looking for "bodyContext.companylist.company" and converting into Array, "bodyContext.elementName" is checked and added to the bodycontext object.

而不是查找“bodyContext.companylist.company”並轉換為Array,檢查“bodyContext.elementName”並將其添加到bodycontext對象。

how to handle this. ElementName variable along with JavaScript object is not recognized. Please help.

怎么處理這個。無法識別ElementName變量以及JavaScript對象。請幫忙。

2 个解决方案

#1


0  

you can JSON.parse(data) then you can fetch data from Javascript object like $.each(Obj,function(key,value){

你可以JSON.parse(數據)然后你可以從Javascript對象獲取數據,如$ .each(Obj,function(key,value){

});

#2


0  

You'll want to use

你會想要使用

bodyContext[elementName]

since

bodyContext.elementName

looks for a field in bodyContext named elementName, not the a field named after the value in elementName.

在bodyContext中查找名為elementName的字段,而不是以elementName中的值命名的字段。

Also, you initialize elementName with "", and this won't match anything on the first iteration.

此外,使用“”初始化elementName,這將與第一次迭代中的任何內容都不匹配。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/10/23/724d5364b44ee296d0a26f90eac1b553.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com