Serialize javascript object to json - javascript

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

Related

Count iterations of an object inside an array

I have a variable returning an array from the DB. Inside that array I need to count the instances of a specific object iteration.
I tried using jQuery.each and logging the output to check but was just getting individual results in the console. I was not getting the desired count. In the sample below I would expect to see:
size 2 - count 1
size 4 - count 2
Sample Output
0: {Email: "example#mai.com", Name: "Bob Smith", ​Number: "555-555-1234", Size: "2"}
1: { Email: "example2#mai.com", Name: "Jenny Girl", ​Number: "222-333-1234", Size: "4"}
2: { Email: "example3#mai.com", Name: "Johnny on the spot", ​Number: "111-777-1234", Size: "4"}
Using jquery what is the best way to achieve this? Is using something like .size?
My code I have attempted:
​​function xyz() {
jQuery.ajax({
data: {action: 'my_action'},
type: 'post',
url: my_ajax.ajax_url,
dataType: 'JSON',
success: function(data) {
jQuery.each(data, function(key,val){
var n = Object.keys(val.Size).size;
console.log(n);
});
​​
​​This gives me an 'undefined' console log readout.
You could store the value of Size as the property of an Object and count:
// Just for demo - that's your data response:
const data = [{Size: "2"}, {Size: "4"}, {Size: "4"}, {Size: "99"}];
const sizes = data.reduce((ob, item) => {
if (!ob.hasOwnProperty(item.Size)) ob[item.Size] = 0;
++ob[item.Size];
return ob;
}, {});
console.log(sizes);
var data = [
{Email: "example#mai.com", Name: "Bob Smith", Number: "555-555-1234", Size: "2"},
{Email: "example2#mai.com", Name: "Jenny Girl", Number: "222-333-1234", Size: "4"},
{Email: "example3#mai.com", Name: "Johnny on the spot", Number: "111-777-1234", Size: "4"}
];
const sizes = data
// collect each "Size" value from the data
.map(e => e.Size)
// use an object to count each instance
.reduce((a, n) => ({...a, [n]: (a[n] || 0) + 1 }), {})
// log each object entry to the console
Object.entries(sizes)
.forEach(([size, count]) => console.log(`size: ${size} count: ${count}`));

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

Accessing Object inside Array

I'm trying to access values inside Firebase array > object.
When I try to access values inside v-for, it works well. But I cannot do this: postDetail.author. It returns undefined. What's the solution?
Since postDetail is an array of object to access properties inside its objects, you need do something like postDetail[Index].prop
var postDetail =[{"author" : "abc", "meta" : "xyz"}];
console.log(postDetail[0].author);
If you want get only author try it:
var postDetails = [{
author: "John",
category: "Tech"
}];
var inner = postDetails.map(function(e) {
return e.autor;
});
console.log(inner);
// Array of object
var persons = [
{
name: "shubham",
age: 22,
comments: ["Good", "Awesome"]
},
{
name: "Ankit",
age: 24,
comments: ["Fine", "Decent"]
},
{
name: "Arvind",
age: 26,
comments: ["Awesome", "Handsome"]
},
{
name: "Ashwani",
age: 28,
comments: ["Very Good", "Lovely"]
}
];
var data = persons.map(person => {
console.log(person.name);
console.log(person.age);
person.comments.map((comment, index) => console.log(index + " " + comment));
});

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

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

Is possible to rewrite all values in array without for loop in javascript?

Let's suppose that we have an array (myArray) with data like this:
0: myArray
content: 'something'
date: '15.5.2015'
name: 'Abc'
1: myArray
content: 'text'
date: '15.5.2015'
name: 'Bla'
2: etc ...
Now for rewriting all values (into e.g. empty string) of one object properties in this array (for example: 'content') I would use for loop like this:
for(var i = 0; i < myArray.length; i++){
myArray[i].content = '';
}
So result of this would be:
0: myArray
content: ''
date: '15.5.2015'
name: 'Abc'
1: myArray
content: ''
date: '15.5.2015'
name: 'Bla'
2: etc ...
My question is: Is possible to do same result without using loop in javascript? Something like this:
myArray[all].content.RewriteInto('');
Tnx for ideas.
Anything you do will end up looping in some fashion. However, you don't have to loop...
because we now have functional array methods! You're probably looking for map or reduce, perhaps both, since you want to transform (map) each element and/or combine them into one (reduce).
As an example, we can take your data and return a string with all of the content fields concatenated using:
var data = [{
content: 'something',
date: '15.5.2015',
name: 'Abc'
}, {
content: 'text',
date: '15.5.2015',
name: 'Bla'
}];
var result = data.map(function(it) {
return it.content;
}).join(' ');
document.getElementById('r').textContent = JSON.stringify(result);
<pre id="r"></pre>
To remove the content field from each item, without modifying the input, you can:
var data = [{
content: 'something',
date: '15.5.2015',
name: 'Abc'
}, {
content: 'text',
date: '15.5.2015',
name: 'Bla'
}];
var result = data.map(function(it) {
return {date: it.date, name: it.name};
});
document.getElementById('r').textContent = JSON.stringify(result);
<pre id="r"></pre>
You should look at the map function.
Use it like this :
myArray.map(function (data) {
return data.content = 'value';
}
As the first comment on your question points out you always have to use a loop, but you could monkey patch the Array using prototype like:
Array.prototype.rewriteInto = function(key, rewriteVal){
for(var k in this){
this[k][key] = rewriteVal;
}
};
var testData = new Array();
testData.push({
content: 'something',
date: '15.5.2015',
name: 'Abc',
});
testData.push({
content: 'something',
date: '15.5.2015',
name: 'bla',
});
console.log(testData);
testData.rewriteInto('content', '');
console.log(testData);
So you don't have to rewrite the loop all the time you want to use this functionality.
See example

Categories

Resources