Create JSON object out of values - javascript

I have these values:
var firstHeader = $('#header0').text(); // 6KP
var secondHeader = $('#header1').text(); // 7KP
var thirdHeader = $('#header2').text(); // 8KP
var first = $('#input0').val(); // 77
var second = $('#input1').val(); //88
var third = $('#input2').val(); // 99
And I need to create a JSON object to have this:
{6KP:77, 7KP:88, 8KP:99}
I tried to do this but without success:
var data = { firstHeader: first, secondHeader: second, thirdHeader: third };
data = JSON.stringify(data, null, ' ');
And my response is this:
{firstHeader: 77, secondHeader:88, thirdHeader:99}
How can I put the values instead of these var names?

You use array notation, e.g.,
var data = {};
data[firstHeader] = first;
If you're using ES6 you can use the shorthand:
var data = {
[firstHeader]: first,
// Etc.
};

You need to use square brackets to evaluate the variable value as a key name:
var data = {};
data[firstHeader] = first;
data[secondHeader] = second;
data[thirdHeader] = third;
WORKING EXAMPLE
var firstHeader = '6KP';
var secondHeader = '7KP';
var thirdHeader = '8KP';
var first = '77';
var second = '88';
var third = '99';
var data = {};
data[firstHeader] = first;
data[secondHeader] = second;
data[thirdHeader] = third;
console.log(JSON.stringify(data));

Replace below line
var data = { firstHeader: first, secondHeader: second, thirdHeader: third };
with
var data ={};
data[firstHeader]= first;
data[secondHeader]= second;
data[thirdHeader]: third ;

Related

Create an a multi diemensional array from different variables in Javascript

How do i create a multi-dimensional array from different javascript variables ?
For example, i have these three variables
var pdate = "|2019-12-26|2019-12-26|2019-12-26"
var products_id = "3354|5009|61927"
var products_category = "ENERGETICS|CASIO|SEIKO"
And i would like to transform them into this
var products_list = []
[0] = {pdate:"2019-12-26",products_id:"3354",products_category:"ENERGETICS"}
[1] = {pdate":"2019-12-26",products_id:"5009",products_category:"CASIO"}
[2] = {pdate:"2019-12-26",products_id:"61927",products_category:"SEIKO"}
Any ideas ?
Thanks
You can use the function split to separate the datas:
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
var arrayPdate = getData(pdate);
var arrayProducts_id = getData(products_id);
var arrayProducts_category = getData(products_category);
var result = []
for (let i = 0; i < arrayPdate.length; i++) {
let jsonObject = {
pdate: arrayPdate[i],
products_id: arrayProducts_id[i],
products_category: arrayProducts_category[i]
}
result.push(jsonObject)
}
console.log(result);
function getData(c) {
return c.split("|")
}
You need use .split function on your string and then use loop with array index for others.
var pdate = "2019-12-26|2019-12-26|2019-12-26";
var products_id = "3354|5009|61927";
var products_category = "ENERGETICS|CASIO|SEIKO";
pdate = pdate.split('|');
products_id = products_id.split('|');
products_category = products_category.split('|');
let arr = [];
for(let i=0; i<pdate.length; i++) {
arr.push({
pdate: pdate[i],
products_id: products_id[i],
products_category: products_category[i]
});
}
console.log(arr);

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

How to parse JSON value from MQTT client to plotly javascript

Hi I have this json type data how can I access P , T , F , W and M data using javascript?
{"PHILMG":[{"P":"10"}, {"T":"5"}, {"F":"0"}, {"W":"0"}, {"M":"0"}]}
so far I tried.
function onMessageArrived(message) {
ss = message.payloadString;
console.log(ss);
// var p = ss.PHILMG.P;
// var time = ss.PHILMG.T;
// var f = ss.PHILMG.F;
// var w = ss.PHILMG.W;
// var m = ss.PHILMG.M;
// var timecollect = [];
// var windcollect = [];
// timecollect.push(time);
// windcollect.push(wind);
// console.log(windcollect);
// var data =
// {
// type:'scatter',
// x: time,
// y: w
// };
// Plotly.newPlot(document.getElementById('PhilMg'), data);
}
But Im getting an error
Object {errorCode: 5, errorMessage: "AMQJS0005E Internal error. Error Message: Cannot r…ajax/libs/paho-mqtt/1.0.1/mqttws31.min.js:19:132)"}
Parse your JSON string with JSON.parse, then loop over the array and push the keys and values to the data which is visualized with Plotly.
var message = '{"PHILMG":[{"P":"10"}, {"T":"5"}, {"F":"0"}, {"W":"0"}, {"M":"0"}]}';
var msg = JSON.parse(message);
var x = [];
var y = [];
var i = 0;
var j;
var k;
for (k in msg) {
for (i = 0; i < msg[k].length; i += 1) {
for (j in msg[k][i]) {
x.push(j);
y.push(msg[k][i][j]);
}
}
}
var data = [{
x: x,
y: y,
type: 'bar'
}];
Plotly.newPlot('myDiv', data);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id='myDiv'></div>
You should use the correct index of the array you have in your object to reach the respective inner object at each assignment.
// var p = ss.PHILMG[0].P;
// var time = ss.PHILMG[1].T;
// var f = ss.PHILMG[2].F;
// var w = ss.PHILMG[3].W;
// var m = ss.PHILMG[4].M;
You can see the log in developer tools,
If you see this,
Object {PHILMG: Array[5]}
You should use the index of the array to get the object, then use key to get the value.
If you see this,
"{"PHILMG":[{"P":"10"}, {"T":"5"}, {"F":"0"}, {"W":"0"}, {"M":"0"}]}"
You should use ss = JSON.parse(ss), and same as above.

Stringify JavaScript object

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"}}

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

Categories