How to convert serialize array value to JSON in javascript - javascript

i have serialize array like this
rate_3=26&rate_8=67&rate_12=98 etc..,
now i need to change this array as json type
{
"ID": "3",
"Rate": "26"
},
{
"ID": "8",
"Rate": "67"
},
{
"ID": "3",
"Rate": "26"
} ..,
etc
so i tried like this but its not working... please some one help me.
var o = {};
var a = table.$('input, select').serialize();
$.each(a, function()
{
if (o[this.name] !== undefined)
{
if (!o[this.name].push)
{
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
}
else
{
o[this.name] = this.value || '';
}
});
return o;
i m using datatable so i just need to get Datatables serialize array only for that used this line
var a = table.$('input, select').serialize();
even i tried with json2.js also but when i use json2.js it forcing the page to submit
var data_2 = JSON.stringify(block_form.serializeArray());

Simple method is to map over the results of a regex match, pushing new objects into the resulting array:
var out = str.match(/\d+=\d+/g).map(function (el) {
var arr = el.split('=');
return { id: arr[0], rate: arr[1] };
});
DEMO
Convert the output array to JSON with JSON.stringify(out).

If your data format is reliably in the rate_N=X& format, you can use simple string splitting to parse out the values. This appears to be similar to how query strings are formatted and, if that's the case, you shouldn't run into (m)any unusual entities.
First, you'll want to break each key-value pair apart (on the &). Then split each pair on the = to produce the key and value. You'll need to parse the ID out of the key (cut the rate_ off the front), which substr will work well for.
var data = "rate_3=26&rate_8=67&rate_12=98";
var pairs = data.split('&').reduce(function(collect, pair) {
var kv = pair.split('=');
var name = kv[0].substr(kv[0].indexOf('_') + 1);
collect.push({
id: name,
rate: kv[1]
});
return collect;
}, []);
document.getElementById('results').textContent = JSON.stringify(pairs);
<pre id="results"></pre>

http://jsfiddle.net/43hnftaf/
var str = 'rate_3=26&rate_8=67&rate_12=98'
var arr = str.split('&').map(function(element) {
return element.replace(/^rate_/, '');
}).map(function(element) {
var elements = element.split('=');
return {
"ID" : elements[0],
"Rate" : elements[1]
};
});
console.log(arr);

Related

get array from the object using map in javascript. but getting array with undefined

I am using map to get the sub part of the array.
var mappingobj = {"custom":[{"head":"202","sub":["302","303"]},{"head":"203","sub":["102"]}],"spec":[]};
var subids = mappingobj.custom.map(function(o, i) {
if(o.head==202){
return o.sub;
}
});
console.log(subids);
I need to get only ["302","303"]. but i am getting the output as [Array[2], undefined].
Basic Idea is that map is to get certain value out of array.
if you don't return anything in map by default undefined will be return and you will get undefined.So use filter to get desired object and than use map to get desired property of that object
var mappingobj = {"custom":[{"head":"202","sub":["302","303"]},{"head":"203","sub":["102"]}],"spec":[]};
var subids = mappingobj.custom.filter(function(o, i) {
if(o.head==202 && o.head){
return o;
}
}).reduce((acc,elem)=>{acc.push(...elem.sub); return acc;},[]);
console.log(subids);
Hi you can try this.
var mappingobj = {
"custom": [{
"head": "202",
"sub": ["302", "303"]
}, {
"head": "203",
"sub": ["102"]
}],
"spec": []
};
var subids = mappingobj.custom.filter(function(o, i) {
if (o.head == 202) {
return o.sub;
}
});
console.log(subids);
Hope this help you.
You can find indexOf of head first and then get sub of mapping.custom
var mappingobj = {"custom":[{"head":"202","sub":["302","303"]},{"head":"203","sub":["102"]}],"spec":[]};
var obj = mappingobj.custom;
var index = obj.map(function (e) { return e.head; }).indexOf("202");
console.log(obj[index].sub);

how to create a map with unique keys from a parsed object in javascript es6/2015?

Lets say I receive a parsed json like below:
[{"a":1},{"a":2},{"a":3}]
The keys are the same which is a.
How do I make each a unique so that the map is usable?'
EDIT1:
Results I want:
let myMap = {}; //I declare my variable
//Then I fetch a json and parse it
fetch(link)
.then(function(response) {
return response.json(); //parse the json string
}).then(function(json) {
myMap = json; //set it to myMap to be used
}
For some reason I having duplicate keys although you guys said the json is unique. Do I have to set the json string to myMap first and then only parse it?
Basically you can use an Object as hash table
var data = [{ "a": 1 }, { "a": 2 }, { "a": 3 }],
object = Object.create(null);
data.forEach(function (el) {
object[el.a] = el;
});
console.log(object);
Or a Map
var data = [{ "a": 1 }, { "a": 2 }, { "a": 3 }],
map = new Map;
data.forEach(function (el) {
map.set(el.a, el);
});
console.log(map.get(1));
The advantage of Map over an Object is, the key can be anything. The key is not converted to string. Maps can have an object or other primitive or not primitive values as key.
Also if you have a single value list or want to make sure it IS unique you can use the index supplied like this:
obj.map((item, index) =>
...
)}
Maybe this?
[{a:1},{a:2},{a:3}].map(function(item, index) { item.id = index; return item; });
Map in javascript doesnot need a unique id, it will iterate through all the value. so it will iterate through all the objects irrespective the fact that the key is same
eg:
var kvArray = [{key:1, value:10}, {key:2, value:20}, {key:3, value: 30}]
var reformattedArray = kvArray.map(function(obj){
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
Well, [{a:1},{a:2},{a:3}] is already unique... but, It's an Array.
so you cannot access an object {a:2, ...} directly but find index with looping.
If I understand your question right way... you want to make new MAP with unique key a how about this way? - reduce can help us. :)
btw, Nina Scholz's answer is right.
let myMap = {}; //I declare my variable
//Then I fetch a json and parse it
fetch(link)
.then(function(response) {
return response.json(); //parse the json string
}).then(function(json) {
// myMap = json; //set it to myMap to be used
myMap = json.reduce(function(p, n) { p[n.a] = n; return p; }, {});
// n.a or n['a'] - primary key (in sample, [1,2,3...])
// "myMap[1].foo", "myMap[2].bar"
// or change KEY as your taste.
myMap = json.reduce(function(p, n) { p['k' + n.a] = n; return p; }, {});
// "myMap.k1.foo", "myMap.k2.bar"
// It's unique but if you want everything...
myMap = json.reduce(function(p, n) {
var k = 'k' + n.a;
if(p[k] !== undefined) { p[k] = n; }
else if(Array.isArray(p[k])) { p[k].push(n); }
else { p[k] = [p[k]] ; }
return p;
}, {});
}

NodeJS - Convert CSV to JSON Object array

I'm trying to convert the below CSV formatted data into a JSON object array,
CSV formatted data: apples,oranges,grapes,peach,pineapple
JSON Object Array: {
fruits: [
{
"name": "apples"
},
{
"name": "oranges"
},
{
"name": "grapes"
},
{
"name": "peach"
},
{
"name": "pineapple"
}
]
}
I referred this npm package https://www.npmjs.com/package/csvtojson and this one with stream parser https://github.com/nicolashery/example-stream-parser, but not sure how this may fit with my need.
Can anyone please suggest a way to convert this CSV data to a JSON object array in the format that's been posted.
Solution for the above query (Please refer the below comments section for more details),
var res = {};
res.fruits = 'apples|1,oranges|2,grapes|3,peach|4,pineapple|5'
.split(',').map(function (fruit) { //as did by #Dmitriy Simushev in the below reply
return {
"name": fruit.split('|')[0],
"value": fruit.split('|')[1]
}
});
document.write('<pre>' + JSON.stringify(res, 0, 2) + '</pre>');
You can use plain javascript, with split and map functions
var res = {};
res.fruits = 'apples|1,oranges|2,grapes|3,peach|4,pineapple|5'
.split(',').map(e => ({
"name": e.split('|')[0],
"value": e.split('|')[1]
}));
document.write('<pre>' + JSON.stringify(res, 0, 2) + '</pre>');
var csv_data = 'apples,oranges,grapes,peach,pineapple';
var csv_array = csv_data.split(',');
var object = {};
var arr = [];
for(var i=0; i<csv_array.length; i++){
arr.push({name:csv_array[i]});
}
object['fruits'] = arr;
console.log(object);
You can easily combine String.prototype.split with Array.prototype.map to achieve the target.
Here is an example of how it could be done:
var data = "apples,oranges,grapes,peach,pineapple";
// Wrap fruits names with object,
var fruits = data.split(',').map(function(fruit) {
return {name: fruit}
});
// Wrap fruits set with outer object.
var json = {fruits: fruits};
// Show the result.
console.dir(json);
As shown in the docs, you can convert your csv file like this
var Converter = require("csvtojson").Converter;
var converter = new Converter({});
converter.fromFile("./yourCSVfile.csv", function(err, result){
// do something with "result", it's json
});
Every answer so far is not reflecting that your data is stored in a file. And I think this is what you are looking for. You can use simple Node.js streams to achieve this:
var fs = require('fs');
var es = require('event-stream');
fs.createReadStream('data.csv')
.pipe(es.split())
.on('data', (row) => {
console.log({
fruits: row.toString().split(',').map((fruit) => {
return {
name: fruit.trim()
}
})
});
});
You need to install event-stream npm install event-stream.

How to filter an array/object by checking multiple values

I'm playing around with arrays trying to understand them more since I tend to work with them alot lately.
I got this case where I want to search an array and compare it's element values to another array which contains values of some selected filters.
For example if I select 3 filters, I want later to write matches in new array - only those which match all 3 filters.
For easier understanding I set up an example on http://jsfiddle.net/easwee/x8U4v/36/
Code is:
var workItems = [
{ "id": 2616, "category": ".category-copy .category-beauty .category-fashion"}, //this is a match
{ "id": 1505, "category": ".category-beauty"}, // NOT
{ "id": 1500, "category": ".category-beauty .category-fashion"}, // NOT
{ "id": 692, "category": ".category-stills .category-retouching"}, // NOT
{ "id": 593, "category": ".category-beauty .category-capture .category-fashion .category-product .category-stills .category-stills-retouching "}, // NOT
{ "id": 636, "category": ".category-beauty .category-copy .category-fashion"}, //this is a match
{ "id": 547, "category": ".category-fashion .category-lifestyle .category-stills .category-stills-retouching "}, // NOT
{ "id": 588, "category": ".category-capture .category-recent-work .category-copy .category-beauty .category-fashion"} //this is a match
];
var filtersArray = [".category-beauty", ".category-fashion", ".category-copy"];
var i;
for (i = 0; i < filtersArray.length; ++i) {
var searchString = filtersArray[i];
console.log('Searching for: ' + searchString);
var filtered = $(workItems).filter(function(){
return this.category.indexOf(searchString);
});
}
console.log('Filtered results: ' + JSON.stringify(filtered, null, 4));
I also tried with
filtered = $.grep(workItems, function(element, index){
return element.category.indexOf(filtersArray[i]);
}, true);
but it matches only the first filter and only if it's at the begining of workItems.category
I've tried many different solutions but can't really make this work. What function should I use to return the desired result?
You can use .filter() method of the Array object:
var filtered = workItems.filter(function(element) {
// Create an array using `.split()` method
var cats = element.category.split(' ');
// Filter the returned array based on specified filters
// If the length of the returned filtered array is equal to
// length of the filters array the element should be returned
return cats.filter(function(cat) {
return filtersArray.indexOf(cat) > -1;
}).length === filtersArray.length;
});
http://jsfiddle.net/6RBnB/
Some old browsers like IE8 doesn't support .filter() method of the Array object, if you are using jQuery you can use .filter() method of jQuery object.
jQuery version:
var filtered = $(workItems).filter(function(i, element) {
var cats = element.category.split(' ');
return $(cats).filter(function(_, cat) {
return $.inArray(cat, filtersArray) > -1;
}).length === filtersArray.length;
});
You can use .filter() with boolean operators ie &&:
var find = my_array.filter(function(result) {
return result.param1 === "srting1" && result.param2 === 'string2';
});
return find[0];
The best way would be to have an array of values to search and then loop the data.
const ids = [1,2,3];
const products = DATA.filter((item) => ids?.includes(item.id));
this trick will help if anyone want to apply filter on the base of more than of property of object.
searchCustomers(){
let tempCustomers = this.customers
if (this.searchValue != '' && this.searchValue) {
tempCustomers = tempCustomers.filter((item) => {
return item.name
.toUpperCase()
.includes(this.searchValue.toUpperCase()) || item.customer_no
.toUpperCase()
.includes(this.searchValue.toUpperCase()) || item.mobno
.toUpperCase()
.includes(this.searchValue.toUpperCase())
})
}
return tempCustomers;
}

Javascript Object push() function

I have a javascript object (I actually get the data through an ajax request):
var data = {};
I have added some stuff into it:
data[0] = { "ID": "1"; "Status": "Valid" }
data[1] = { "ID": "2"; "Status": "Invalid" }
Now I want to remove all objects with an invalid status (but keep everything the ordering same):
var tempData = {};
for ( var index in data ) {
if ( data[index].Status == "Valid" ) {
tempData.push( data );
}
}
data = tempData;
In my mind, all of this should work, but I am getting an error that tempData.push is not a function. I understand why it isn't the same as an array, but what could I do otherwise?
push() is for arrays, not objects, so use the right data structure.
var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
if ( data[index].Status == "Valid" ) {
tempData.push( data );
}
}
data = tempData;
Objects does not support push property, but you can save it as well using the index as key,
var tempData = {};
for ( var index in data ) {
if ( data[index].Status == "Valid" ) {
tempData[index] = data;
}
}
data = tempData;
I think this is easier if remove the object if its status is invalid, by doing.
for(var index in data){
if(data[index].Status == "Invalid"){
delete data[index];
}
}
And finally you don't need to create a var temp –
You must make var tempData = new Array();
Push is an Array function.
Javascript programming language supports functional programming paradigm so you can do easily with these codes.
var data = [
{"Id": "1", "Status": "Valid"},
{"Id": "2", "Status": "Invalid"}
];
var isValid = function(data){
return data.Status === "Valid";
};
var valids = data.filter(isValid);
I hope this one might help you.
let data = [];
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
let tempData = [];
tempData= data.filter((item)=>item.Status!='Invalid')
console.log(tempData)
tempData.push( data[index] );
I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.
I assume that REALLY you get object from server and want to get object on output
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])
var data = { 5: { "ID": "0", "Status": "Valid" } }; // some OBJECT from server response
data = { ...data,
0: { "ID": "1", "Status": "Valid" },
1: { "ID": "2", "Status": "Invalid" },
2: { "ID": "3", "Status": "Valid" }
}
// solution 1: where output is sorted filtred array
let arr=Object.keys(data).filter(k=> data[k].Status!='Invalid').map(k=>data[k]).sort((a,b)=>+a.ID-b.ID);
// solution2: where output is filtered object
Object.keys(data).map(k=> data[k].Status=='Invalid' && delete data[k])
// show
console.log('Object',data);
console.log('Array ',arr);
Mozilla actually shows you how to handle objects with push by chaining push to the call method:
"push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.
Note that we don't create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.
const obj = {
length: 0,
addElem(elem) {
// obj.length is automatically incremented
// every time an element is added.
[].push.call(this, elem);
},
};
// Let's add some empty objects just to illustrate.
obj.addElem({});
obj.addElem({});
console.log(obj.length);
// → 2
Note that although obj is not an array, the method push successfully incremented obj's length property just like if we were dealing with an actual array."
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
You are getting that error because data.push only works with array, not object.
So here is what you can do:
var data = {};
data[0] = { "ID": "1"; "Status": "Valid" }
data[1] = { "ID": "2"; "Status": "Invalid" }
var tempData = {};
for ( var index in data ) {
if ( data[index].Status == "Valid" ) {
tempData[index] = data[index];
}
}
data = tempData;
Do :
var data = new Array();
var tempData = new Array();

Categories

Resources