0

I have a json key value object that contains...

let myObject = {
"data[contentblocks][0][title]": "something",
"data[contentblocks][1][title]": "some other title",
"data[seo][description]": "some description",
"data[headerimage]": "something.jpg"
}

I'm trying to loop over the object and create an object that matches the square bracket structure...

let data = {
   contentblocks: [
     {title: "something"},
     {title: "some other title"}
   ],
   seo: { "description": "some description"}
   headerimage: "something.jpg"    
}

etc...

I tried looping over the object

for(let key in formData)
        {
            let finalValue = formData[key];
            console.log(key, finalValue)
        }

and was going to simply do an eval(key+ " = " + finalValue) but gives an undefined error. I'm wondering if there is a simple way to do this that I'm not entirely seeing. I'd rather do this with native javascript, but I do have jquery on the site as well.

I am considering doing a loop and exploding the keys, but I fear I'm going down a path that is more complex than I need.

Nathan Leggatt
  • 398
  • 1
  • 6
  • 18

1 Answers1

0

You can't eval the keys in myObject, those keys are not valid key values unless wrapped in quotes. No way to quote those keys? Set variables with those names instead:

let myObject = {
    "data[contentblocks][0][title]": "something",
    "data[contentblocks][1][title]": "some other title",
    "data[seo][description]": "some description",
    "data[headerimage]": "something.jpg"
}

let data = {
    contentblocks: [
        {title: ""},
        {title: ""}
    ],
    seo: { "description": "some description"},
    headerimage: "something.jpg"    
}

// Solution 1: Add key variables
contentblocks = "contentblocks";
title = "title";
seo = "seo";
description = "description";
headerimage = "headerimage";

for(let key in myObject){
    let finalValue = myObject[key];
    // console.log(key, finalValue)
    eval(`${key} = "${finalValue}";`);
}

console.log(data);

// Solution 2: Add quotes to keys
for(let key in myObject){
    let finalValue = myObject[key];
    // console.log(key, finalValue)

    let key2 = key;
    key2 = key2.replace(/\[/g,"['").replace(/\]/g,"']");
    eval(`${key2} = "${finalValue}";`);
}

console.log(data);
Dee
  • 7,455
  • 6
  • 36
  • 70