Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to dynamically create a sqlite insert string with node. I have:

function update_json_obj_into_table(tablename, obj, search_condition) {

  const insertValues = Object.entries(obj).reduce((acc, [k,v]) => acc.push(`${k} = ${v}`), []);

  const insertValuesString = Array.prototype.join.call(insertValues, '/');

 console.log(insertValuesString);
 console.log(`UPDATE ${tablename} SET ${insertValues} WHERE ${search_condition}`);
 // db.run(`UPDATE ${tablename} SET ${insertValuesString} WHERE search_condition ;`);
};

When I run it :

 const obj = {Code: 'A1'};
 update_json_obj_into_table('mytable', obj, 'search_condition') 

I get:

 UPDATE mytable SET 1 WHERE search_condition.

Obviously the insertValues is not working correctly. I was expecting:

Code = 1

but its coming out as '1' . What am I doing wrong?

question from:https://stackoverflow.com/questions/65649395/reduce-with-obj-key-value-not-working-as-expected

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
116 views
Welcome To Ask or Share your Answers For Others

1 Answer

.push returns the new length of the array, not the mutated array. While you could put the .push on its own line and return the array on the next line:

function update_json_obj_into_table(tablename, obj, search_condition) {

  const insertValues = Object.entries(obj).reduce((acc, [k, v]) => {
    acc.push(`${k} = ${v}`);
    return acc;
  }, []);

  const insertValuesString = Array.prototype.join.call(insertValues, '/');

  console.log(insertValuesString);
  console.log(`UPDATE ${tablename} SET ${insertValues} WHERE ${search_condition}`);
  // db.run(`UPDATE ${tablename} SET ${insertValuesString} WHERE search_condition ;`);
};


const obj = {
  Code: 'A1'
};
update_json_obj_into_table('mytable', obj, 'search_condition')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...