Javascript创建未知维度大小的数组

时间:2016-08-03 09:20:56

标签: javascript arrays multidimensional-array reference

虽然我正在编写Javascript几年,至少想过知道它的大部分特性和问题,但我今天遇到了一个新的。

我有一个设备数组,每个设备都包含一个路径属性。在此路径中,属性也是一个数组。

[
    { // Device object
        path: [1]
        name: "Device 1",...
    },
    { // Device object
        path: [1,3]
        name: "Device 13",...
    },
    { // Device object
        path: [1,3,1]
        name: "Device 131",...
    }...
]

此path属性表示数组中的路径,我必须创建。所以上面的结构应该导致以下结果(我知道它不是有效的JS):

[
1 => {
    name: "Device 1",
    children: [
        3 => {
            name: "Device 13",
            children: [
                1 => {
                    name: "Device 131",
                    children: [],...
                },
            ],...
        },
    ],...
},
]

在任何其他语言中,例如php我会使用引用或指针,然后循环遍历路径数组:

$newArr = [];
$ptr = &$newArr;
foreach($path as $key){
    $ptr = &$ptr[$key].children;
}

我能想到在JS中做这样的事情的唯一方法是使用eval。但也许你有更好的想法。

澄清我想要的东西:第一个结构应以某种方式处理并“转换为第二个结构”。第三个也是最后一个代码片段是我在PHP中使用的方法。

谢谢

卢卡

2 个答案:

答案 0 :(得分:1)

试试这个(未经测试):

    class myTextField(QPlainTextEdit):

        def __init__(self):
            super(myTextField, self).__init__()
            ...


        def focus(self):
            self.focusInEvent(QFocusEvent( QEvent.FocusIn ))
            # Now the cursor blinks at the end of the last line.
            # But typing on your keyboard doesn't insert any text.
            # You still got to click explicitly onto the widget..

        ...

    ###

答案 1 :(得分:0)

您可以通过传递结果对象的当前嵌套级别和路径的id(属性键)来使用reduce。每当设备条目不存在时,它就会被添加到当前对象中。

var result = {};
devices.forEach(function(device){

    device.path.reduce(function(obj, id){
        if( !obj.hasOwnProperty(id) )
            obj[id] = { name: device.name, children: {} };
        return obj[id].children;
    }, result);

});

var devices = [{
  path: [1],
  name: "Device 1"
},{
  path: [1, 2],
  name: "Device 12"
},{
  path: [1, 3],
  name: "Device 13"
},{
  path: [1, 3, 1],
  name: "Device 131"
}];


var result = {};
devices.forEach(function(device) {

  device.path.reduce(function(obj, id) {
    if (!obj.hasOwnProperty(id))
      obj[id] = {
        name: device.name,
        children: {}
      };
    return obj[id].children;
  }, result);

});
console.log(result);

相关问题