0

i want to manufacture the result of mysql in node js

i want to make the result like this

[ { "m_idx" :1 , "contents" : { "m_name" : "a", "m_name" : "b", } }, "m_idx" :2, "contents" : { "m_name" : "c", } } ] 

but my result is

{ "m_idx": 1, "contents": [ { "m_name": "a" } ] }, { "m_idx": 1, "contents": [ { "m_name": "b" } ] }, 

i don't know how to manufacture the result could any one help me...? pls this is what i practiced code

let result = []; let categories = []; connection.query(sql, function (err, rows) { if (res.status(200)) { rows.forEach(function (row, index) { let variable = { m_idx: row.m_idx, contents: [] }; categories.push(variable); variable.contents.push({ m_name: row.m_name, name: row.name, }) }); res.json(categories); } }); 

and my database result is like this

----- |1|a| |1|b| |2|c| ----- 

1 Answer 1

1

i guess the contents you want is an array rather than an object, cause there shouldn't be same properties in a same object.

maybe this will help you.

const rows = [ {"m_idx": 1, "m_name": "a"}, {"m_idx": 1, "m_name": "b"}, {"m_idx": 2, "m_name": "c"} ] const map = new Map(); rows.forEach(row => { if (map.get(row.m_idx) === undefined) { map.set(row.m_idx, { "m_idx": row.m_idx, "contents": [{"m_name": row.m_name}] }); } else { map.get(row.m_idx).contents.push({"m_name": row.m_name}); } }); const result = []; map.forEach((v, k) => { result.push(v); }); console.log(result); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.