javascript - Javascript:通过对象迭代循环
问题描述
给定以下 json 对象结构,我需要获取每个目标对象的 id 和值,以及行星、人和主题的对象值。
var data = {
"goals": [{
"id": "goal-09",
"colour": "#FD6925",
"priority": "People",
"theme": "Sustainable Infrastructure",
"title": "Industry, Innovation & Infrastructure",
"value": 4
},
{
"id": "goal-12",
"colour": "#BF8B2E",
"priority": "Planet",
"theme": "Responsible Consumption",
"title": "Responsible Consumption & Production",
"value": 3
},
{
"id": "goal-13",
"colour": "#3F7E44",
"priority": "Planet",
"theme": "Environment",
"title": "Climate Action",
"value": 1
}
],
"planet": 50,
"people": 50,
"themes": {
"Sustainable Infrastructure": 4,
"Responsible Consumption": 3,
"Environment": 1
}
}
我尝试了几个循环,但这有点困难,你最多可以有 17 个目标和最多 5 个不同的主题。
Object.keys(data).forEach(function(key) {
alert(key+" "+data[key]); // logs keys in myObject
});
这是我测试https://jsfiddle.net/dhzpqo4n/的地方,我将从 sessionStorage 获取 json 字符串。
最终目标是构造一个 sql update 语句将这些存储在具有以下结构的表中
更新 我提出了以下脚本,这是朝着正确方向迈出的一步,可以使用每个目标的值构造我的 sql 更新语句。
let i = 0
while (data.goals[i].id) {
document.write(data.goals[i].id + "=" + data.goals[i].value + " ");
i++
}
这给出了goal-09=4 goal-12=3 goal-13=1
https://jsfiddle.net/3r49zqsu/4/
解决方案
创建一个数组并按如下方式推送结果:
1) ifval
是一个数组,然后循环遍历它以获取对象的id
and value
。然后将其推入result
数组。
2)如果是对象,则先将其转换为key=value
形式,然后将其推送到结果数组中。
3)否则将结果推送为默认key=value
形式
然后最后加入数组space
。而已。
var data = {
goals: [
{
id: "goal-09",
colour: "#FD6925",
priority: "People",
theme: "Sustainable Infrastructure",
title: "Industry, Innovation & Infrastructure",
value: 4,
},
{
id: "goal-12",
colour: "#BF8B2E",
priority: "Planet",
theme: "Responsible Consumption",
title: "Responsible Consumption & Production",
value: 3,
},
{
id: "goal-13",
colour: "#3F7E44",
priority: "Planet",
theme: "Environment",
title: "Climate Action",
value: 1,
},
],
planet: 50,
people: 50,
themes: {
"Sustainable Infrastructure": 4,
"Responsible Consumption": 3,
Environment: 1,
},
};
let result = [];
for (let key in data) {
const val = data[key];
if (Array.isArray(val)) {
const temp = val.map(({ id, value }) => `${id}=${value}`);
result = result.concat(temp);
} else if (typeof val === "object") {
const temp = Object.entries(val).map(([k, v]) => `${k}=${v}`);
result = result.concat(temp);
} else {
result.push(`${key}=${val}`);
}
}
console.log(result.join(" "));
你可以简化一点
var data = {
goals: [
{
id: "goal-09",
colour: "#FD6925",
priority: "People",
theme: "Sustainable Infrastructure",
title: "Industry, Innovation & Infrastructure",
value: 4,
},
{
id: "goal-12",
colour: "#BF8B2E",
priority: "Planet",
theme: "Responsible Consumption",
title: "Responsible Consumption & Production",
value: 3,
},
{
id: "goal-13",
colour: "#3F7E44",
priority: "Planet",
theme: "Environment",
title: "Climate Action",
value: 1,
},
],
planet: 50,
people: 50,
themes: {
"Sustainable Infrastructure": 4,
"Responsible Consumption": 3,
Environment: 1,
},
};
let result = [];
function pushInFinalResult(arr) {
result = [...result, ...arr];
}
for (let key in data) {
const val = data[key];
if (Array.isArray(val)) {
pushInFinalResult(val.map(({ id, value }) => `${id}=${value}`));
} else if (typeof val === "object") {
pushInFinalResult(Object.entries(val).map(([k, v]) => `${k}=${v}`));
} else {
pushInFinalResult([`${key}=${val}`]);
}
}
console.log(result.join(" "));
删除空格和-
var data = {
goals: [
{
id: "goal-09",
colour: "#FD6925",
priority: "People",
theme: "Sustainable Infrastructure",
title: "Industry, Innovation & Infrastructure",
value: 4,
},
{
id: "goal-12",
colour: "#BF8B2E",
priority: "Planet",
theme: "Responsible Consumption",
title: "Responsible Consumption & Production",
value: 3,
},
{
id: "goal-13",
colour: "#3F7E44",
priority: "Planet",
theme: "Environment",
title: "Climate Action",
value: 1,
},
],
planet: 50,
people: 50,
themes: {
"Sustainable Infrastructure": 4,
"Responsible Consumption": 3,
Environment: 1,
},
};
let result = [];
function pushInFinalResult(arr) {
result = [...result, ...arr];
}
for (let key in data) {
const val = data[key];
if (Array.isArray(val)) {
pushInFinalResult(
val.map(({ id, value }) => `${id.replace("-", "")}=${value}`) // change
);
} else if (typeof val === "object") {
pushInFinalResult(
Object.entries(val).map(([k, v]) => `${k.replace(" ", "")}=${v}`) // change
);
} else {
pushInFinalResult([`${key}=${val}`]);
}
}
console.log(result.join(" "));
推荐阅读
- matplotlib - 如何使用 sklearn 提高 MultinomialNB() 的准确度分数并使用 matplotlib 在图形中可视化结果?
- java - 如何在休眠中的 session.get() 方法中获取动态值?
- python - 带有 contains_eager 的 sqlalchemy 模型实例作为 arg 提交给 ThreadPoolExecutor
- performance - ChannelGroup 发送处理程序级别
- jenkins - Jenkinsfile cifsPublisher 没有使用通配符复制正确的文件
- python-3.x - 我应该如何使用 asyncio 读取将在 python 中阻塞的套接字
- swift - 在 DispatchQueue (Swift) 中分配时对象的生命周期
- hyperledger - REST API post 的事务处理器函数
- java - Java 泛型:无法转换
进入 - javascript - 通过JS获取输入字段内的复选框名称