0

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

2
  • 1
    You could do it manually or use a query builder like knex.js (if building queries from js objects is a common problem in your app) Commented Dec 4, 2020 at 8:23
  • No idea on knex.js but how to do it manually? will it be messy? Commented Dec 4, 2020 at 8:29

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

4 Comments

Great solution.... but what if the value for "CASE_0" is {}?
We dont know the expected ouput in that case, could you add it to the question?
The output would be just {}
Can't understand. If filled, you get a string. If no value, you get an object? I would suggest to add the case explicitly in the question
0

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

1 Comment

This accepted answer doesnt fit the expected output of the question... Returns an array of objects instead of one object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.