How to merge or push to an $.param array? - javascript

I have made a serialized array/ object using:
var data = $.param([{name: "commentID", value: commentID}, {name: "comment", value: comment}])
Then later on before my Ajax request I need to add another $.param array, how can I do this? I tried $.merge but it messes up the array?

You can do something like this,
var data = $.param([{name: "commentID", value: commentID}, {name: "comment", value: comment}]);
var newData = $.param([{name: "newID", value: newID}]);
data = data + "&" + newData;
Another way to do is have an array and use $.param before ajax call,
var data = [{name: "commentID", value: commentID}, {name: "comment", value: comment}];
data.push({name: "newID", value: newID});
and at the end
data = $.param(data);

Related

Javascript How to push item in object

var data = {items: [
{id: "1", name: "Snatch", type: "crime"}
]};
And I would like to add the mark's key.
So the result would be:
var data = {items: [
{id: "1", name: "Snatch", type: "crime", mark:"10"}
]};
How can I do ?
I tried to do data.items.push({"mark": "10"}) but it adds another object which is not what I want.
Thanks.
Access the correct index and simply set the property
data.items[0].mark = "10";
You may not need push here because you want to create a new key to n existig object. Here you need dot (.) to create a new key
var data = {
items: [{
id: "1",
name: "Snatch",
type: "crime"
}]
};
data.items[0].mark = "10";
console.log(data)
And, if you want add “mark” property to all the items:
data.items.forEach(function(item, index) {
data.items[index].mark = 10;
}

Convert String to an Array in JS

In my project I have a use case like the below:
I have a response Array like below,
(4) [{…}, {…}, {…}, {…}]
0:{header: 0, name: "Name", field: "Id"}
1:{header: 3, name: "LastName", field: "Agreement__c"}
2:{header: 3, name: "LastName", field: "Amount__c"}
3:{header: 3, name: "LastName", field: "BIC__c"}
length:4
from the above I convert the above array to String by using,
JSON.stringify(responseArray) and store it in a string field.
After that I want to do some manipulation dynamically to that value of that field. So when I get the value back from the field it came as like below,
[{"header":0,"name":"Name","field":"Id"},
{"header":3,"name":"LastName","field":"Agreement__c"},
{"header":3,"name":"LastName","field":"Amount__c"},
{"header":3,"name":"LastName","field":"BIC__c"}]
Anyone please help me to convert the above string response to an Array in Javascript like as follows,
index 0 -> {"header":0,"name":"Name","field":"Id"}
index 1 -> {"header":3,"name":"LastName","field":"Agreement"}
I have tried with the split function but couldn't able to achieve the exact need.
Put square brackets at the beginning and end of your string and call JSON.parse:
$ node
> const text = `{"header":0,"name":"Name","field":"Id"},
{"header":3,"name":"LastName","field":"Agreement"},
{"header":3,"name":"LastName","field":"Amount"},
{"header":3,"name":"LastName","field":"BIC"}`
> JSON.parse(`[${text}]`)
[ { header: 0, name: 'Name', field: 'Id' },
{ header: 3, name: 'LastName', field: 'Agreement' },
{ header: 3, name: 'LastName', field: 'Amount' },
{ header: 3, name: 'LastName', field: 'BIC' } ]
you can use following code sample first append "[" at begging of your string and "]" at end of your string so your string will be well formatted as JSON array then it is so easy to parse it using JSON.parse built in function
a = '['+'{"header":0,"name":"Name","field":"Id"}, {"header":3,"name":"LastName","field":"Agreement"}, {"header":3,"name":"LastName","field":"Amount"}, {"header":3,"name":"LastName","field":"BIC"}'+"]"
var myarray = JSON.parse(a);
yes, JSON.parse is the real easy answer for this.
You just need some basic string manipulations, By the way, I changed your string into a valid syntax
var str="{\"header\":0,\"name\":\"Name\",\"field\":\"Id\"},{\"header\":3,\"name\":\"LastName\",\"field\":\"Agreement\"},{\"header\":3,\"name\":\"LastName\",\"field\":\"Amount\"},{\"header\":3,\"name\":\"LastName\",\"field\":\"BIC\"}";
str=str.replace(/},{/g,"}|{");
var arr = str.split("|");
var json = [];
for(i=0; i<arr.length; i++){
json.push(JSON.parse(arr[i]));
}
//console.log(json);
console.log(json[0]);
console.log(json[1]);
try this
var textstr = '[{"header":0,"name":"Name","field":"Id"},{"header":3,"name":"LastName","field":"Agreement"}, {"header":3,"name":"LastName","field":"Amount"}, {"header":3,"name":"LastName","field":"BIC"}]';
var textstr2 = JSON.parse(textstr);
console.log(textstr2)

Serialize javascript object to json

I m trying to serialize java script object to json. Here is my code so far:
var info = {};
...
$.each(data, function (key, value) {
info["name"] = value.name;
info["id"] = value.id;
});
...
console.log(JSON.stringify(info));
But this returns me : {}
It would be grateful if some one can suggest me a way to get the out-put like below :
[{name: "John", id: "1"},
{name: "Anna", id: "2"},
{name: "Peter", id: "3"}]
Thank you.
You need to:
Change your info variable to an array, rather than a JSON object.
Change your code to:
var info = [];
$.each(data, function (key, value) {
info.push({
name: value.name,
id: value.id
});
});

Required help in JSON

I have this below json data.
[{"start_date":"2014-06-27","count":"21","value":"134"},{"start_date":"2014-06-28","count":"17","value":"120"},{"start_date":"2014-06-29","count":"21","value":"138"},{"start_date":"2014-06-30","count":"9","value":"121"},{"start_date":"2014-07-01","count":"12","value":"112"},{"start_date":"2014-07-02","count":"19","value":"132"}]
I trying to plot this a line chart using highcharts.
I wanted to convert my data to something like this.
[{
name: "count",
data: [21, 17 .......]
},{
name: "value",
data: [134, 120, .......]
}]
How can I format my data like that using jquery?
I use AJAX to get that data from a database.
Any help will be very helpful.
Thanks in advance.
USE
var res= YOUR JSON DATA
var data=$.parseJSON(res);
var count= new Array();
var val=new Array();
$(data).each(function(i,u){
count.push(u.count);
val.push(u.value);
});
now you can use
[{
name: "count",
data: count
},{
name: "value",
data: val
}]
var array = [{"start_date":"2014-06-27","count":"21","value":"134"},{"start_date":"2014-06-28","count":"17","value":"120"},{"start_date":"2014-06-29","count":"21","value":"138"},{"start_date":"2014-06-30","count":"9","value":"121"},{"start_date":"2014-07-01","count":"12","value":"112"},{"start_date":"2014-07-02","count":"19","value":"132"}]
var chartOptions = [];
var countData = {name: "count", data: []};
var valueData = {name: "value", data: []};
array.forEach(function(value, index){
countData.data.push(value.count);
valueData.data.push(value.value);
});
chartOptions.push(countData);
chartOptions.push(valueData);
I would build the JSON structure required by highcharts server side, before returning it in the AJAX call. There simply adding it directly to highcharts.
This will be more efficient then letting the users browser make the formating.

AngularJS : How to concat two arrays?

I have following arrays with values (i am generating the values on go)
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
I want to concatenate these two objects to get the following result
[{Name:''},{ Key: '', Value: '' }]
Plunker link , somehow that's not working either
when I click on the add row button it will add another row for key and value text boxes only not for name, I can add n no of rows and when I click on Submit it should show the kev value pair as
[{Name:''},{ Key: '', Value: '' },{ Key: '', Value: '' },{ Key: '', Value: '' }.....so on]
Thanks
Not sure why you want to build an array of mismatched objects. That seems to me to be asking for trouble. I would suggest possibly doing the following:
$scope.objects = [{Name: '', Elements: []}];
Then you can easily manage multiple objects who have elements:
(I use underscore http://underscorejs.org/)
$scope.addElementToObject = function(objName, element){
_.where($scope.mergedArray, {Name: objName}).Elements.push(element);
};
Then you can add to the list of elements for that object without having to eval the object in the elements array on each use.
If you still want/need to merge arrays of mismatched objects, it would be the following:
$scope.objectName = [{ Name: '' }];
$scope.propertiesElement = [{ Key: '', Value: '' }];
$scope.mergedArray = $scope.objectName.contact($scope.propertiesElement);
$scope.addElement = function(element){
$scope.mergedArray.push(element);
};
Then, in your click event code:
$scope.addElement({ Key: 'someKey', Value: 'Some Value' });
I hope this helps.

Categories

Resources