Stringify JavaScript object - javascript

I'm looking to stringify an object.
I want in output like this
{"1":{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, "2": {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}}
But I get this
{"valeur":"dalebrun","usager":"experttasp","date":"2013-08-20 16:41:50"}, {"valeur":"test","usager":"experttasp","date":"2013-08-20 16:41:50"}
What I do
var objVal = {}; //value....
var data = {}; //other value....
var object = $.extend({}, objVal, data); //concat the object
JSON.stringify(object);

When you concat the object, you get an array; you want a map with two elements, using the id "1" and "2"
var objVal = {}; //value....
var data = {}; //other value....
var object = {}
object["1"] = objVal;
object["2"] = date;
JSON.stringify(object);

I found the solution !
I do an for loop on the object. And I iterate on each element in the object. Thank you for your help. The answer of #Giovanni help me to found the solution.
Solution:
var data = {}; //values....
var objVal = {}; //other values....
var final = {};
var index = 1;
for(var key in data)
{
final[index] = data[key];
index = index + 1;
}
final[index] = objVal;
JSON.stringify(final);
And the output is :
{"1":{"valeur":"dfgdfg","usager":"experttasp","date":"2013-08-23 10:36:54"},"2":{"valeur":"uuuuuuuuuu","commentaire":"defg","usager":"experttasp","date":"2013-08-23 10:37:26"},"3":{"valeur":"uuuuuuuuuu","commentaire":"yesssss","usager":"experttasp","date":"2013-08-23 10:38:38"}}

Related

javascript always pushes the same object

Do you have any idea why this code always adds the last object?
Because I used
var obj = {}
and
var newBase = Object.assign({}, baseJson)
but code always use the same reference?
module.exports = (csv, baseJson) => {
var lines=csv.split("\n");
var result = [];
var headers=lines[0].split(";");
for(var i=1;i<lines.length;i++){
var obj = {};
var newBase = Object.assign({}, baseJson);
obj["case"] = "Scenario";
obj["request"] = newBase;
obj["response"] = {
responseCode: "5",
actionCode: "0",
approvalCode: "98765X",
}
var currentline=lines[i].split(";");
var responseTags = ["responseCode", "actionCode", "approvalCode"];
for(var j=0;j<headers.length;j++){
headers[j] = headers[j].replace('\r','');
currentline[j] = currentline[j].replace('\r','')
if (headers[j] == "Scenario") {
obj["case"] = currentline[j];
}
else if (responseTags.indexOf(headers[j]) > -1 ){
obj["response"][headers[j]] = currentline[j];
}
else {
saveValue(obj["request"], headers[j], currentline[j]);
}
}
result.push(obj);
}
I tried almost everything but I could not manage to create a new object. It uses the same reference. This code is in node.js.
Thank you
Object.assign may not clone inner objects and it just takes same reference, try stringify and parse it.
var newBase = JSON.parse(JSON.stringify(baseJson));
Refer to know more : What is the most efficient way to deep clone an object in JavaScript?
This is because Javascript vars scoped to functions, not blocks. Effectively in your code obj is declared outside of the loop and it's properties mutated.
let should solve the problem:
for(var i=1;i<lines.length;i++){
let obj = {};
...
result.push(obj);
}

How to convert array to object then assign to new variable

I want to convert data stored in one variable from an array to an object, then assign that converted data to another variable.
For example, take:
options = ["226:39"];
and convert ["226:39"] to {"226":"39"}, then assign the converted data to the convertedOptions variable.
How would I do that?
While the other answers are correct for the sample value you mentioned in the question, using substring instead of split will handle the case where the value may need to contain a ":" character.
var options = ["226:39", "ratio:226:39"];
var convertedOptions = {};
for(var i = 0; i < options.length; i++){
var separatorIndex = options[i].indexOf(":");
if(separatorIndex > -1) {
var name = options[i].substring(0, separatorIndex);
var value = options[i].substring(separatorIndex + 1, options[i].length);
convertedOptions[name] = value;
}
}
console.log(convertedOptions);
You can split the string using the : separator, create your convertedOptions object, and then assign.
var options = ['226:39'];
var splitOptions = options[0].split(':');
var convertedOptions = {};
convertedOptions[splitOptions[0]] = splitOptions[1];
console.log(convertedOptions);
You can do it by spliting the element of options by ':':
var options = ["226:39"];
convertedOptions = {};
var el = options[0].split(':');
convertedOptions[el[0]] = el[1];
console.log(convertedOptions);
OR:
var options = ["226:39"];
convertedOptions = {};
var [prop, value] = options[0].split(':');
convertedOptions[prop] = value;
console.log(convertedOptions);
OR:
var options = ["226:39"];
var [prop, value] = options[0].split(':');
convertedOptions = { [prop]: value };
console.log(convertedOptions);
You could split the string and map an object for each element of options for a new property.
var options = ["226:39"],
convertedOptions = Object.assign(
...options.map(a => (([k, v]) => ({ [k]: v }))(a.split(':')))
);
console.log(convertedOptions);
Use String#replace to format the string as JSON, and then convert to an object using JSON#parse:
var options = ["226:39"];
var convertedOptions = JSON.parse(options[0].replace(/([^:]+):([^:]+)/, '{"$1":$2}'));
console.log(convertedOptions);

JSON.stringify with square brackets

I have a JS object:
var source = {};
source.quantity = 1;
source.text = 'test';
Now I JSON it:
var json = JSON.stringify(source);
json looks like this:
{"quantity":"1","text":"test"}
I would like it to be like this:
[{"quantity":"1"},{"text":"test"}]
Ho can I do this?
Get all the keys as an Array them map them to Objects as key-value pairs from source
JSON.stringify(
Object.keys(source)
.map(
function (e) {
var o = {};
o[e] = source[e];
return o;
}
)
); // "[{"quantity":1},{"text":"test"}]"
var json = JSON.stringify([
{quantity: "1"},
{text: "test"}
]);
I guess this is not possible but you can do this:
var source = {};
source.quantity = 1;
source.text = 'test';
var result = [];
for(var i in source) {
var obj = {};
obj[i] = source[i];
result.push(obj);
}
var json = JSON.stringify(result);
I hope this can help you.

How do I split two strings and make a key-value pair in javascript

var ma = "jim";
var nu = "123";
var splitit = ma.split("");
var splitit2 = nu.split("");
for (i=0; i<=splitit.length;i++) {
var bach = {splitit[i]:splitit2[i]};
}
alert(bach);
You probably want
var bach = {}; // create the object
for (i=0; i<=splitit.length;i++) {
bach[splitit[i]]=splitit2[i]; // set a property according to the arrays
}
instead of
for (i=0; i<=splitit.length;i++) {
var bach = {splitit[i]:splitit2[i]};
}
Use
var ma = "jim";
var nu = "123";
var splitit = ma.split("");
var splitit2 = nu.split("");
var bach = {};
for (i=0; i<=splitit.length;i++) {
bach[splitit[i]] =splitit2[i];
}
Demo: Fiddle
You cannot use variables for property names in object literals, they always get interpreted literally. And you probably want only one bach object, instead of creating a new one each loop turn.
var bach = {};
for (i=0; i<=splitit.length;i++) {
bach[splitit[i]] = splitit2[i];
}
alert(JSON.stringify(bach));

Object gets changed even if I do not make any operations with it

Can someone tell me why in the following code snippet the value of ColumnNames is changed at the position of the debugger? It takes the same value as tempColumns after tempColumns[k] = modi[i].data[k];.
var addRecords= [];
var columns = ["Column1","Column2","Column4","Column5"]
var columnNames = {};
var modi = [{
data: {
Column1: 'bla'
}
},{
data:{
Column2: 'test'
}
}];
var tempColumns = {};
for( var n in columns){
var column = columns[n];
columnNames[column] = "";
}
for(var i in modi){
tempColumns = columnNames;
for(var k in modi[i].data){
tempColumns[k] = modi[i].data[k];
debugger;
}
addRecords.push(tempColumns);
}
It is happening because you assigned columnNames to tempColumns before your debugger. In javascript values of objects are passed by reference which means that after line:
tempColumns = columnNames
tempColumns and columnNames point to the same position in memory.
You need to make a copy of the object. When you say tempColumns = columnNames then they both point to the same memory. with the following method you can make a copy from an object: JSON.parse(JSON.stringify(obj))
obj = {1:"hi", 2:"by"};
newobj = JSON.parse(JSON.stringify(obj));
newobj["1"] = "hello";
console.log(obj);
console.log(newobj);

Categories