首页 > 解决方案 > 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/

标签: javascriptarraysobject

解决方案


创建一个数组并按如下方式推送结果:

1) ifval是一个数组,然后循环遍历它以获取对象的idand 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(" "));


推荐阅读