-2

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.

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.

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.

sessionStorage

the end goal is to construct a sql update statement to store these in a table with the following structure

enter image description here

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.

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/

David Garcia
  • 3,056
  • 18
  • 55
  • 90
  • 1
    You could use `for..in` loop. BTW what do you want? – DecPK Jun 30 '21 at 23:30
  • Familiarize yourself with [how to access and process nested objects, arrays or JSON](/q/11922383/4642212) and how to [create objects](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer) and use the available [`Object`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object#Static_methods) and [`Array`](//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Static_methods) methods (both static and on prototype). – Sebastian Simon Jun 30 '21 at 23:31
  • 2
    `data.goals.forEach(...)` – Barmar Jun 30 '21 at 23:32
  • @Barmar— "*…as well as planet, people, and theme's object value also*". – RobG Jun 30 '21 at 23:38
  • 1
    You should show the data structure you're trying to create, as "*…fetch the id and value…*" could mean just copying the object and leaving out the unwanted properties, or it might mean gathering the wanted properties and organising them differently. – RobG Jun 30 '21 at 23:42
  • @RobG those aren't arrays, there's nothing to iterate – Barmar Jun 30 '21 at 23:42
  • Guys, thank you for your answers, what I am looking to get is a string such as the following `goal-09=4 goal-12=3 goal-13=1 planet=50 people=50 people=50 Sustainable Infrastructure=4 Responsible Consumption=3 Environment=1` so that I can construct an update syntax for my code @decpk @robg @barmar – David Garcia Jul 01 '21 at 03:49
  • `let i = 0 while (data.goals[i].id) { document.write(data.goals[i].id + "=" + data.goals[i].value + " "); i++ }` gives me goal-09=4 goal-12=3 goal-13=1 which is a step in the right direction – David Garcia Jul 01 '21 at 04:13
  • @DavidGarcia Answered please check is this what you want? – DecPK Jul 01 '21 at 04:39

2 Answers2

1

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. Then push it into result array.

2) If it is an object then first convert it into key=value form and then push it into result array.

3) else push the result as default key=value form

then finally join the array with 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(" "));
DecPK
  • 24,537
  • 6
  • 26
  • 42
  • This is really good, does what I need, thank you for saving me countless hours of research, i have one last big ask, how hard is it to replace the dash in the goal-01 to goal01 and to remove spaces in the theme names, Sustainable Infrastructure to SustainableInfrastructure – David Garcia Jul 01 '21 at 05:10
  • You just have to make 2 changes and you are done – DecPK Jul 01 '21 at 05:28
  • 1
    @DavidGarcia code edited and see Is this what you want? – DecPK Jul 01 '21 at 05:30
0

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.

  • Hey Proximity, what I am looking to get is to generate a string such as this `goal-09=4 goal-12=3 goal-13=1 planet=50 people=50 people=50 Sustainable Infrastructure=4 Responsible Consumption=3 Environment=1` to be used in a sql update statement – David Garcia Jul 01 '21 at 03:49