简体   繁体   English

Javascript:通过对象迭代循环

[英]Javascript: Iterate Loop through object

Given the following json object structure, I need to fetch the id and value for each of the goals object as well as planet, people, and theme's object value also.给定以下 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
  }
}

I have tried a couple of loops but this is a bit difficult, also you can have up to 17 goals and up to 5 different themes.我已经尝试了几个循环,但这有点困难,你也可以有多达 17 个目标和多达 5 个不同的主题。

Object.keys(data).forEach(function(key) {
  alert(key+" "+data[key]); // logs keys in myObject
});

This is where I am testing https://jsfiddle.net/dhzpqo4n/ and I will be fetching the json string from sessionStorage.这是我测试https://jsfiddle.net/dhzpqo4n/ 的地方,我将从 sessionStorage 获取 json 字符串。

会话存储

the end goal is to construct a sql update statement to store these in a table with the following structure最终目标是构造一个 sql update 语句,将它们存储在具有以下结构的表中

在此处输入图片说明

update I've come up with the following script which is a step in the right direction to construct my sql update statement with the values if each of the goals.更新我想出了以下脚本,这是朝着正确方向迈出的一步,可以使用每个目标的值构建我的 sql 更新语句。

let i = 0
while (data.goals[i].id) {
  document.write(data.goals[i].id + "=" + data.goals[i].value + " ");
  i++
}

Which gives goal-09=4 goal-12=3 goal-13=1 https://jsfiddle.net/3r49zqsu/4/这给出了goal-09=4 goal-12=3 goal-13=1 https://jsfiddle.net/3r49zqsu/4/

Create an array and push the result as follows:创建一个数组并推送结果如下:

1) if val is an array then loop through it to get the object's id and value . 1)如果val是一个数组,则循环遍历它以获取对象的idvalue Then push it into result array.然后将其推入result数组。

2) If it is an object then first convert it into key=value form and then push it into result array. 2)如果它是一个对象,则首先将其转换为key=value形式,然后将其推送到结果数组中。

3) else push the result as default key=value form 3) else 将结果推送为默认的key=value形式

then finally join the array with space .然后最后用space加入数组。 That's it.就是这样。

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

You can simplify a bit你可以简化一点

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

Removing spaces and -删除空格和-

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

Do you mean something like this?你的意思是这样的吗?

{goals: data.goals.map(k=>{return {id:k.id,value:k.value}}),planet:data.planet,people:data.people,themes:data.themes}

What happens here is it loops through all the goals and returns an object of only the id and the value.这里发生的是它遍历所有目标并返回一个只有 id 和值的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM