首页 > 解决方案 > 将json对象路径从字符串转换为对象

问题描述

我有一个 json 键值对象,其中包含...

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: "something"},
     {title: "some other title"}
   ],
   seo: { "description": "some description"}
   headerimage: "something.jpg"    
}

ETC...

我尝试循环对象

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

并且打算简单地做一个 eval(key+ " = " + finalValue) 但给出一个未定义的错误。我想知道是否有一种我没有完全看到的简单方法来做到这一点。我宁愿用原生 javascript 来做这件事,但我在网站上也有 jquery。

我正在考虑做一个循环并爆炸键,但我担心我会走上一条比我需要的更复杂的道路。

标签: javascript

解决方案


您不能eval输入 中的键myObject,除非用引号括起来,否则这些键不是有效的键值。没有办法引用那些键?改为使用这些名称设置变量:

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);

推荐阅读