如何在JavaScript中将重复的字符串解析为对象数组?

时间:2015-11-19 19:12:08

标签: javascript

我在一个长字符串中有几个对象的属性,用“|”分隔,如下所示:

branches = "001|lat1|lon1|Name1|002|lat2|lon2|Name2|003|lat3|lon3|Name3|004|lat4|lon4|Name4"
headers = "ID|Latitude|Longitude|Name" //name of attributes 
fieldCount = "4" //4 attributes per object

我需要将它转换为JavaScript中的propper对象数组,如下所示:

[
    {
        "ID": "001",
        "latitude": "lat1",
        "longitude": "lon1",
        "name": "Name1"
    },
    {
        "ID": "002",
        "latitude": "lat2",
        "longitude": "lon2",
        "name": "Name2"
    },
    {
        "ID": "003",
        "latitude": "lat3",
        "longitude": "lon3",
        "name": "Name3"
    },
    {
        "ID": "004",
        "latitude": "lat4",
        "longitude": "lon4",
        "name": "Name4"
    }
]

问题是如何实现这个目标?

2 个答案:

答案 0 :(得分:1)

您需要做的就是拆分字符串以创建数组并循环遍历它们从分支数组中为标题数组中的每个项目弹出前项目

var branches = "001|lat1|lon1|Name1|002|lat2|lon2|Name2|003|lat3|lon3|Name3|004|lat4|lon4|Name4";
var headers = "ID|Latitude|Longitude|Name";
branches = branches.split("|");
headers = headers.split("|");
var array=[];
while(branches.length){
    var x = {};
    for(i=0;i<headers.length;i++){
        x[headers[i]]=branches.shift();
    }
    array.push(x);
}
console.log(array);

答案 1 :(得分:0)

var branches = "001|lat1|lon1|Name1|002|lat2|lon2|Name2|003|lat3|lon3|Name3|004|lat4|lon4|Name4";
var headers = "ID|Latitude|Longitude|Name"; //name of attributes 

var branchArray = branches.split("|");
var headerArray = headers.split("|");
var numFields = headerArray.length; //fieldCount is redundant
var objects = []; //result will be stored here
var currentObj = {};

for(var i = 0; i < branchArray.length; ++i) {
    var fieldIndex = i % numFields;
    // When we just put in the last field
    if(fieldIndex === (numFields - 1)) {
        if(currentObj) {
            objects.push(currentObj);
            currentObj = {};
        }
    }

    currentObj[headerArray[fieldIndex]] = branchArray[i];
}

有一些边缘情况,例如当分支中的字段数不能被标题中的字段数整除时,但您没有明确指定如何处理这些字段。