Javascript-将INI文件解析为嵌套的关联数组 [英] Javascript - Parsing INI file into nested associative array
问题描述
我是Java语言的新手,无法将INI格式的文件解析为嵌套对象.
I'm new to Javascript and I'm having trouble parsing an INI formatted file into nested objects.
我的文件格式如下:
ford.car.focus.transmission=standard
ford.car.focus.engine=four-cylinder
ford.car.focus.fuel=gas
ford.car.taurus.transmission=automatic
ford.car.taurus.engine=V-8
ford.car.taurus.fuel=diesel
purchased=Ford Taurus
我希望结构如下:
{ ford:
{ car:
{ focus:
{
transmission: 'standard',
engine: 'four-cylinder',
fuel: 'gas'
}
}
{ taurus:
{
transmission: 'automatic',
engine: 'V-8',
fuel: 'diesel'
}
}
}
purchased: 'Ford Taurus'
}
我将文件按行存储在数组中,在'\ n'上拆分.我正在尝试编写一个将在循环中调用的方法,并像这样传递我的全局对象:
I'm storing the file in lines in an array, splitting on '\n'. I'm trying to write a method that would be called in a loop, passing my global object like this:
var hash = {};
var array = fileData.toString().split("\n");
for (i in array) {
var tmp = array[i].split("=");
createNestedObjects(tmp[0], tmp[1], hash);
}
这应该让我可以访问哈希对象中的值,如:
This should let me access the values in the hash object like:
hash.ford.car.focus.fuel
# 'gas'
hash.purchase
# 'Ford Taurus'
I've tried something like what was suggested here: Javascript: how to dynamically create nested objects using object names given by an array, but it only seems to set the last item in the nest.
{ fuel: 'diesel',
purchased: 'Ford Taurus' }
我失败的尝试看起来像这样:
My unsuccessful attempt looks like this:
createNestedObjects(path, value, obj) {
var keys = path.split('.');
keys.reduce(function(o, k) {
if (k == keys[keys.length-1]) {
return o[k] = value;
} else {
return o[k] = {};
}
}, obj);
}
但是,它只会返回嵌套值的最后一个值:
However, it will only return the last value for the nested values:
{ ford: { car: { taurus: { fuel: 'diesel' } } },
purchased: 'Ford Taurus' }
推荐答案
该函数需要在分配中间键之前检查中间键是否已经存在.
The function needs to check whether an intermediate key already exists before assigning to it.
createNestedObjects(path, value, obj) {
var keys = path.split('.');
keys.reduce(function(o, k) {
if (k == keys[keys.length-1]) {
return o[k] = value;
} else if (o[k]) {
return o[k];
} else {
return o[k] = {};
}
}, obj);
}
这篇关于Javascript-将INI文件解析为嵌套的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!