【问题标题】:Create a nested array from a string从字符串创建嵌套数组
【发布时间】:2021-08-22 00:02:08
【问题描述】:

我想使用具有这种结构的纯 JS 从字符串创建一个数组:

vehicles:[ 
  {
    information:{brand: audi, model: a3, year: 2007},
    characteristics: {motor: CDI, potency: X} 
  },
  {
    information:{brand: bmw, model: x3, year: 2002},
    characteristics: {motor: TDI, potency: Y} 
  }
]

我的字符串是

vehicles[0].information.brand = audi;
vehicles[0].information.model = a3;
vehicles[0].information.year = 2007;
vehicles[0].characteristics.motor = CDI;
vehicles[0].characteristics.potency = X;

vehicles[1].information.brand = bmw;
vehicles[1].information.model = x3;
vehicles[2].information.year = 2002;
vehicles[2].characteristics.motor = TDI;
vehicles[2].characteristics.potency = Y;

我能够创建对象部分,但我在数组索引以及如何创建这种父子关系方面遇到了困难。

【问题讨论】:

    标签: javascript arrays multidimensional-array ecmascript-6 nested


    【解决方案1】:

    新的贡献者。如果你能搜索一下,你会发现很多像你这样的问题。

    let input = `vehicles[0].information.brand = audi;
    vehicles[0].information.model = a3;
    vehicles[0].information.year = 2007;
    vehicles[0].characteristics.motor = CDI;
    vehicles[0].characteristics.potency = X;
    
    vehicles[1].information.brand = bmw;
    vehicles[1].information.model = x3;
    vehicles[2].information.year = 2002;
    vehicles[2].characteristics.motor = TDI;
    vehicles[2].characteristics.potency = Y`.replace(/\n/g, "").split(";")
    
    
    function update(obj, keys, value) {
        const lastProp = keys.pop();
        keys.reduce((obj, key, i, arr) =>
            obj[key] ??= Number.isInteger(+arr[i + 1]) ? [] : {}, obj)[lastProp] = value;
        return obj;
    }
    
    let obj = {};
    
    for (const str of input) {
        let [key, value] = str.split(" = ");
        update(obj, key.match(/\w+/g), value)
    }
    
    console.log(obj)

    【讨论】:

    • 赞this one,只有10k+用户可以看到这个话题。
    猜你喜欢
    • 1970-01-01
    • 2019-07-07
    • 2019-02-08
    • 1970-01-01
    • 1970-01-01
    • 2016-02-12
    • 2021-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多