-1

I want to create an array from a string using pure JS with this structure:

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} 
  }
]

and my strings are

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;

I was able to create the object part, but I'm having struggle with array indexes and how to create this parent-child relation.

1 Answers1

0

New contributor. If you could search you would find so many questions like yours.

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)
Nur
  • 2,361
  • 2
  • 16
  • 34
  • like [this one](https://stackoverflow.com/questions/67294090/access-and-replace-a-value-in-deep-of-an-object-with-a-string-path-in-javascript/67295369#67295369), only 10k plus users can saw this topic. – Nur Jun 03 '21 at 21:53