Bratty Neal
Bratty Neal

Reputation: 152

How to build a SQL query from a json in react?

I have a requirement to modify a JSON to a JSON having the values in a SQL query format. To better explain.

{
 "CASE_0": {"fact_dark":"CHC_Fill"},
 "CASE_2": {"Itc_sun":"SEA_Ont"}
}

The result should be having the json values as an sql query leaving the keys as it is. So the resulting query will be:

{
CASE_0: "fact_dark = 'CHC_Fill'", 
CASE_2: "Itc_sun = 'SEA_Ont'"
}

I could've proceeded with regex but I couldn't figure it out well. Any elegant ES6 based solution to this?. Please folks help me out on this. TIA

Upvotes: 0

Views: 936

Answers (2)

Tigran Abrahamyan
Tigran Abrahamyan

Reputation: 776

First, we have to transform the object into the array, for this, we use the Object.entries();.

Then we go through the array and create a new array using map, and inside map we create an object.

Then in the console.log(); we deployment the array using spread operator and get our object.

const data = {
  "CASE_0": {"fact_dark":"CHC_Fill"},
  "CASE_2": {"Itc_sun":"SEA_Ont"}
};

const result = Object.entries(data).map(n => {
  return {
    [n[0]]: `${Object.keys(n[1])} = '${Object.values(n[1])}'`,
  };
});

console.log(Object.assign(...result));

Upvotes: 0

Rashomon
Rashomon

Reputation: 6762

Here is a solution using ES6 reduce and entries method, string templates, array destructuring and spread operator:

const input = {
 "CASE_0": {"fact_dark":"CHC_Fill"},
 "CASE_2": {"Itc_sun":"SEA_Ont"}
}

const output = Object.entries(input).reduce((result, [CASE, caseValue]) => {
  const [[key, value]] = Object.entries(caseValue)
  return {...result, [CASE]: `${key} = '${value}'`}
}, {})

console.log(output)

Upvotes: 1

Related Questions