javascript - 将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。
我正在考虑做一个循环并爆炸键,但我担心我会走上一条比我需要的更复杂的道路。
解决方案
您不能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);
推荐阅读
- apache - 重新启动时Apache服务器时间更改
- javascript - socket.io SSL / HTTPS 在客户端出现 404 错误 / 无法连接到服务器
- c# - 如何使用在本地系统下运行的 Windows 服务以不同的用户身份调用控制台应用程序?
- asp.net - 为所有页面使用一个到 API 的连接
- javascript - 创建不带反斜杠的 JSON
- javascript - 条件不起作用并仍在提交表单
- java - 如何获取 Windows 的 IcedTea 浏览器插件(OpenJDK 浏览器 java 插件)?
- spring-boot - Spring boot 启动日志到文件
- javascript - Javascript按条件在循环中添加延迟
- r - 使用 rvest follow_link 循环浏览网页列表