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.
Related
I have following JSON string :
{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}
I want location_id as
3,2
Simple:
var data = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var result = data.map(function(val) {
return val.location_id;
}).join(',');
console.log(result)
I assume you wanted a string, hence the .join(','), if you want an array simply remove that part.
You could add brackets to the string, parse the string (JSON.parse) and map (Array#map) the property and the join (Array#join) the result.
var string = '{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}',
array = JSON.parse('[' + string + ']'),
result = array.map(function (a) { return a.location_id; }).join();
console.log(result);
obj=[{"name":"Marine Lines","location_id":3}, {"name":"Ghatkopar","location_id":2}]
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x].location_id);
console.log(res.join(","));
var json = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var locationIds = [];
for(var object in json){
locationIds.push(json[object].location_id);
}
console.log(locationIds.join(","));
You can also look into .reduce and create a string manually
var d = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}]
var location_id_str = d.reduce(function(p, c) {
return p ? p + ',' + c.location_id : c.location_id
},'');
console.log(location_id_str)
try this
var obj = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var output = obj.map( function(item){
return item.location_id;
});
console.log( output.join(",") )
var arr = [{"name":"Marine Lines","location_id":3},{"name":"Ghatkopar","location_id":2}];
var location_array = [];
for( var i = 0; i < arr.length; i++ )
{
location_array.push( arr[i].location_id );
}//for
var location_string = location_array.join(",");
console.log(location_string);
Note: You may need to use JSON.parse() if the arr is in string format initially.
You can use for..of loop
var arr = [{
"name": "Marine Lines",
"location_id": 3
}, {
"name": "Ghatkopar",
"location_id": 2
}];
var res = [];
for ({location_id} of arr) {res.push(location_id)};
console.log(res);
I am passing a large number of variables to a http server. Instead of writing a long command prompt, I want to set up the variables as a object literal. If I set it up statically it works fine. But I want to populate the object in a loop.
This works:
var data= { T1: 123,
R1: 'L',
T2: 3434,
R2: 'R'};
$.post(url,data, get_outcome);
But I want to write a loop that does this, and I need to understand how I would populate the object literal with my variable names and values. (the example is just to demonstrate) If I try it this way it fails:
var data=[];
data.push({T1: 123});
data.push({T2: 3434});
data.push({R1: 'L'});
data.push({R2: 'R'});
$.post(url,data, get_outcome);
I have even tried this:
var data=[];
var a,val,name;
name={"T1","T2","R1","R2"};
val={"123","3434","L","R"};
for(a=0;a<4;a++){
data.push({name[a]:val[a]});
}
$.post(url,data,get_outcome);
The final function should work like this:
function Save(var values, var val){
var a,name;
var data=[];
for(a=0;a<values;a++){
name="T"+(a+1);
data.push({name: val[a]});
}
$.post(url,data,get_outcome);
}
What am I doing wrong ?
I implemented the solution suggested by Rajiv as follows:
function save(){
var data=[];
function dataPush(name, val) {
var obj = {};
obj[name] = val;
data.push(obj);
}
//eg hardcoded values
dataPush('T1',123);
dataPush('T2',3123);
dataPush('R1',"R");
dataPush('R2',"L");
// values stored in arrays elsewhere
for(a=2;a<max;a++){
temp="T"+(a+1);
dataPush(temp,T[a]);
temp="R"+(a+1);
dataPush(temp,R[a]);
}
$.post(url,data, get_outcome);
}
You are creating an array. Create like this
var data={};
data.T1 = 123;
data.T2 = 3434;
data.R1 = 'L';
data.R2 = 'R';
$.post(url,data,get_outcome);
And When using the array
var data={};
var a,val,name;
name={"T1","T2","R1","R2"};
val={"123","3434","L","R"};
for(a=0;a<4;a++){
data[name[a]] = val[a];
}
var data = {};
var name = ["T1", "T2", "R1", "R2"];
var val = [123, 3434, "L", "R"];
name.forEach(function(el, index){
data[el] = val[i];
});
Will produce
var data= { T1: 123,
R1: 'L',
T2: 3434,
R2: 'R'
};
var arry = [];
function dataPush(name, val) {
var obj = {};
obj[name] = val;
arry.push(obj);
}
KeyName =["T1","T2","R1","R2"];
KeyVal = ["123", "3434", "L", "R"];
for (var i = 0; i < KeyName.length; i++) {
dataPush(KeyName[i], KeyVal[i]);
}
console.log(arry);
After that used this array
All I understood from your question is that you need to create a object and send that to server. The object needs to have some properties that you wanna add dynamically, rather than statically.
If that's it, you can do so as :
var localData = [{key1: 'val1'},{key2: 'val2'},{key3: 'val3'}, {key4: 'val4', key5:'val5'}] // your data that you want to send
function createPayload(localData) {
var payload = {};
localData.forEach(function(o) {
for(var key in o) {
payload[key] = o[key];
}
});
return payload;
}
var objectToSend = createPayload(localData);
console.log(objectToSend);
I have a object, need to parse the below data
var data= [{"obj1":"2122"},{"obj2":"123"}]
to get both the keys and values in javascript. I yried to use:
var obj = JSON.parse(data);
for(var prop in data) {
if(data.hasOwnProperty(prop))
console.log(prop);
}
The values that are obtained in console are
Object {obj1: "2122"}
Object {obj2: "123"}
But I need to access the values seperately and not as object. How to retrieve it from that object?
JSON.parse is use to parse JSONString to Javascript Object.
You can not use it directly on a JavaScript Object ...
Anyway, your object is an array so you may do :
var arr = JSON.parse(data);
arr.forEach(function(elementObject){
var keys = Object.keys(elementObject);
keys.forEach(function(key){
console.log(key + ":"+elementObject[key]);
})
});
Cheers
Here you will get the values in array "values".
var data= [{"obj1":"2122"},{"obj2":"123"}]
data = JSON.stringify(data);
var values = [];
JSON.parse(data, function (key, value) {
if (typeof(value) != "object") {
values.push({[key]:value});
// values.push(value); //if you need a value array
}
});
Use Array#map and extract keys of the object in the callback. Iterate them to gain the value of each key using Array#forEach
var data = [{
"obj1": "2122"
}, {
"obj2": "123"
}];
var op = data.map(function(item) {
var keys = Object.keys(item);
var arr = [];
keys.forEach(function(key) {
arr.push(item[key]);
});
return arr;
});
console.log(op);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Try this code use $.each function to parse object..
var data= [{"obj1":"2122"},{"obj2":"123"}]
$.each(data, function(key, val) {
$.each(val, function(k, v) {
console.log('key ='+k);
console.log('value ='+v);
alert('key = '+k+', value = '+v);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Try this one..
var obj = JSON.parse('[{"obj1":2122},{"obj2":123}]');
obj.forEach(function(ElementObject){
var keys=Object.keys(ElementObject);
console.log(keys[0],ElementObject[Object.keys(ElementObject)]);
}
);
JsFiddle
First:
var data = [{"obj1":"2122"},{"obj2":"123"}]
This line will create an Array. No need for:
var obj = JSON.parse(data);
If you want to access via key/value you need to restructure your data.
var data = [{key:"obj1",value:"2122"},{key:"obj2", value:"123"}];
for( var index in data)
{
var item = data[index];
console.log(item.key);
console.log(item.value);
}
Alternately you can map:
var keys = [{
"obj1": "2122"
}, {
"obj2": "123"
}];
var op = data.map(function(item) {
var keys = Object.keys(item);
var arr = [];
keys.forEach(function(key) {
console.log(key);
arr.push(key);
});
return arr;
});
var i=0;
for(var i=0;i<op.length;i++)
{
console.log(i);
var pair=data[i];
console.log(pair);
var key=op[i][0];
console.log(key);
var value=pair[key];
console.log(value);
}
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"}}
I want to convert a REST style url into a javascript literal, like this:
from:
var url = "/a/b/c/d";
to:
var obj = {
a:{
b:{
c:{
d:{}
}
}
}
};
How would you do this?
You can probably condense it but here's a solution :
var u = '/a/b/c/d';
var t = u.split('/');
var o = {};
for (var i=t.length; i-->1; ) {
var temp = o;
o = {};
o[t[i]] = temp;
}
The result is o.
My attempt:
var url = '/a/b/c/d';
var fun = function(a) {
var res = {};
res[a[0]] = a.length == 1 ? {} : fun(a.slice(1));
return res;
};
// obj has what you need
var obj = fun(url.split('/').slice(1));
// OTHER EXAMPLE
var t = ['that', 'is', 'so', 'fun'];
console.log(fun(t));
// above returns object: {that: { is: { so: { fun: {} }}}}