JavaScript根据字符串值构建嵌套数组

时间:2018-09-10 13:39:09

标签: javascript arrays

从我的数据源中,我得到的值是;

USA        |Arizona
USA        |Florida
UK         |England |Northamptonshire
UK         |England |Derbyshire
UK         |Wales   |Powys
Switzerland|Lucern

这些是在列中重复的纯文本值。

我需要将它们动态地构建到嵌套数组中

source: [
    {title: "USA",  children: [
      {title: "Arizona"},
      {title: "Florida"}
    ]}
  ],

按照https://github.com/mar10/fancytree/wiki/TutorialLoadData

不幸的是,今天我的大脑停止工作了,我看不到任何优雅的方式。

非常感谢任何指针。

所以我最终使用Oskar的帖子解决了这个问题

function getNestedChildren(arr, parent) {
    var out = []
    for(var i in arr) {
        if(arr[i].parent == parent) {
            var children = getNestedChildren(arr, arr[i].id)

            if(children.length) {
                arr[i].children = children
            }
            out.push(arr[i])
        }
    }
    return out
}

http://oskarhane.com/create-a-nested-array-recursively-in-javascript/

这将构建嵌套数组。

为确保存在推断出的值(例如,位于层次结构中但不是唯一值的USA)。

		var CountryArray = CountryText.split("|");
	
		// Variables to hold details of each section of the Country path being iterated
		var CountryId = '';
		var CountryParentPrefix = '';
		var CountryParent = '';

		// Iterate each section of the delimeted Country path and ensure that it is in the array
		for(var i in CountryArray) 
		{

			var CountryId = CountryParentPrefix+CountryArray[i];
	
			// Find the Country id in the array / add if necessary
			var result = FlatSource.filter(function (Country) { return Country.id == CountryId });
			if (result.length == 0) {
					// If the Country is not there then we should add it
					var arrCountry = {title:CountryArray[i], parent:CountryParent, id:CountryId};
					FlatSource.push(arrCountry);
			}
			

			// For the next path of the heirarchy
			CountryParent = CountryId;
			CountryParentPrefix = CountryId+'|';
		}

我没有使用Sven的建议,但我怀疑它同样有效。

1 个答案:

答案 0 :(得分:0)

将其转换为JSON:

var str = '"USA|Arizona","USA|Florida","UK|LonelyIsland","UK|England|Northamptonshire","UK|England|Derbyshire","UK|Wales|Powys","UK|England|London|Soho","Switzerland|Lucern';

var jsonStr = "[[" + str.replace(/,/g,'],[') + "\"]]";
jsonStr = jsonStr.replace(/\|/g,'","');
var nested = JSON.parse(jsonStr);

然后与父母和孩子一起玩。

function findObject(array, key, value) {
    for (var i=0; i<array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
    return null;
}

function obj(arr){
    this.title = arr.shift();
}

obj.prototype.addChild = function(arr){
    var tmp = new obj(arr);
    if(typeof this.children === 'undefined'){
        this.children = new Array();
        result = this.children[this.children.push(tmp)-1];
    }else{
        result = findObject(this.children, 'title', tmp.title);
        if(!result)
            result = this.children[this.children.push(tmp)-1];
    }
    return result;
}

obj.prototype.addChildren = function(arr){
    var obje = this;
    while(arr.length>0)
        obje = obje.addChild(arr);
}


var finArr = [];
for(i=0; i<nested.length; i++){
    var recc = new obj(nested[i]);
    if(oldObj = findObject(finArr, 'title', recc.title)){
        oldObj.addChildren(nested[i]);
    }else{
        if(nested[i].length>0)
                recc.addChildren(nested[i]);
        finArr.push(recc);        
    }
}

console.log('------------------------------------------')
console.log(JSON.stringify(finArr));
console.log('--------------------The End---------------')