Convert Array to JSON Array - javascript

How do I convert
["ID:2","ID:3","ID:4"]
to
[{
"ID":2
},
{
"ID":3
},
{
"ID":4
}]
because this type of data i have to send to my webservice

For getting an array with objects, you could split the strings and build a new object with the wanted property and the numerical value.
var data = ["ID:2","ID:3","ID:4"],
result = data.map(function (s) {
var p = s.split(':'),
t = {};
t[p[0]] = +p[1];
return t;
});
console.log(result);

var newArrayOfObjs =arr.map((item)=> {
var obj = {};
var splitItems = item.split(':');
obj[splitItems[0]] = splitItems[1];
return obj;
}
You'll have to split the string on ':' and set the 0th element as key and 1st element as value.

var aryExample = ["ID:2","ID:3","ID:4"], aryNew = [];
for( var i in aryExample ) {
aryNew.push({ID:Number(aryExample[i].split(":")[1])});
}
console.dir(aryNew);
That should do it.

Related

Filter Multidimensional Array

I have my dataset configured as
var x = [
{"phaseName":"Initiation","phaseID":"595e382f1a1e9124d4e2600c"},
{"phaseName":"Execution","phaseID":"595e38321a1e9124d4e2600d"}
]
I want to write some function which give the output of filtered data.
For example
var y ="Initiation"
samplefunction(y)
and i get the whole line of {"phaseName":"Initiation","phaseID":"595e382f1a1e9124d4e2600c"}
Use Array#filter
var x = [{
"phaseName": "Initiation",
"phaseID": "595e382f1a1e9124d4e2600c"
},
{
"phaseName": "Execution",
"phaseID": "595e38321a1e9124d4e2600d"
}
];
function filter(phaseName) {
return x.filter(item => {
return item.phaseName === phaseName;
});
}
console.log(filter('Initiation'));
You can also use a simple for loop:
var x = [{
"phaseName": "Initiation",
"phaseID": "595e382f1a1e9124d4e2600c"
},
{
"phaseName": "Execution",
"phaseID": "595e38321a1e9124d4e2600d"
}
];
var y = "Initiation";
function samplefunction(value) {
var newArr = new Array(); //creating a new array to store the values
for (var i = 0; i < Object.keys(x).length; i++) { //looping through the original array
if (x[i].phaseName == value) {//check if the phase name coresponds with the argument
newArr.push(x[i]); //push the coressponding value to the new array
}
}
return newArr; //return the new array with filtered values
}
var result = samplefunction(y);
console.log(result);
You could test all properties for the wanted value and filter the array.
function filter(array, value) {
return array.filter(function (object) {
return Object.keys(object).some(function (key) {
return object[key] === value;
});
});
}
var data = [{ phaseName: "Initiation", phaseID: "595e382f1a1e9124d4e2600c" }, { phaseName: "Execution", phaseID: "595e38321a1e9124d4e2600d" }];
console.log(filter(data, "Initiation"));

unwanted keys in JSON object

hi i am creating a JSON object after executing a loop. the problem is the JSON object have additional keys. i don't want that keys. that keys are generated by me. for arraigning the json according my requirement. this is code i am using for create my JSON object
var bankdata = data;
var updatebankdata = {}
for (var key in bankdata) {
var id = +key.substr(key.length - 1);
if (isNaN(id)) {
updatebankdata[0] = updatebankdata[0] || {};
updatebankdata[0][key] = bankdata[key];
} else {
var uniqid=$("#bankaccount"+id).attr("uniq_id");
updatebankdata[id] = updatebankdata[id] || {};
var field = key.substring(0, key.length - 1);
updatebankdata[id][field] = bankdata[key];
updatebankdata[id]["uniquid"] = uniquid;
}
}
return updatebankdata;
}
my bank data is like
{bankname1: "new", micrcode1: "mkkk", comments1: "commentsfvfdv", bankname2: "bankfgname", micrcode2: "micrfgcode"…}
i want to change it into like this way
[{bankname1: "new", micrcode1: "mkkk", comments1:
"commentsfvfdv"},{bankname2: "bankfgname", micrcode2: "micrfgcode"}]
but still it getting like this .its not good
{"0":{bankname1: "new", micrcode1: "mkkk", comments1:
"commentsfvfdv"},"1":{bankname2: "bankfgname", micrcode2: "micrfgcode"}
what is the mistake in my code?
You need to use an array instead of an object. Like so:
function func(data) {
var bankdata = data;
var updatebankdata = []; // ARRAY instead of Object
for (var key in bankdata) {
var id = +key.substr(key.length - 1);
if (isNaN(id)) {
updatebankdata[0] = updatebankdata[0] || {};
updatebankdata[0][key] = bankdata[key];
} else {
var uniqid=$("#bankaccount"+id).attr("uniq_id");
updatebankdata[id] = updatebankdata[id] || {};
var field = key.substring(0, key.length - 1);
updatebankdata[id][field] = bankdata[key];
updatebankdata[id]["uniquid"] = uniqid; // CHANGED to "uniqid" to match variable declaration above, not the key on the left is still "uniquid"
}
}
return updatebankdata;
}
Then you can get result like:
JSON.stringify(func({name: 'someval', val: 123}));
"[{"name":"someval","val":123}]"
assign
var updatebankdata = [];
then push your object to array like this
updatebankdata.push(yourObject)

Serialize/Reg ex

I use serialize function to get all the values of my form.
My problem is how can i extract only the value in the generated url string of the serialize function and split it into an array.
var input = $('#addForm').serialize();
deviceBrand=itemBrand&deviceModel=itemModel&deviceSerial=itemSerial&deviceType=Desktop&deviceStatus=Available&deviceDesc=item+description //generated url string
i need string function to extract each string between "=" and "&" and put each String into an array.
Don't use serialize, use serializeArray. It creates an array of objects of the form {name: "xxx", value: "yyy" } that you can process more easily.
var input = $("#addForm").serializeArray();
var values = input.map(x => x.value);
You can also make an object with all the name: value properties:
var object = {};
input.map(x => object[x.name] = x.value);
try this code to unserialize the string,
(function($){
$.unserialize = function(serializedString){
var str = decodeURI(serializedString);
var pairs = str.split('&');
var obj = {}, p, idx, val;
for (var i=0, n=pairs.length; i < n; i++) {
p = pairs[i].split('=');
idx = p[0];
if (idx.indexOf("[]") == (idx.length - 2)) {
// Eh um vetor
var ind = idx.substring(0, idx.length-2)
if (obj[ind] === undefined) {
obj[ind] = [];
}
obj[ind].push(p[1]);
}
else {
obj[idx] = p[1];
}
}
return obj;
};
})(jQuery);

how can i transmission array to object with lodash?

I have an array like as below
var arr = [ 'type=A', 'day=45' ];
var trans = { 'type': 'A', 'day': 45 }
Please write easiest and most efficient way :)
You could split the string and check if the value isNaN for string or take the numerical value.
var array = [ 'type=A', 'day=45', 'bar=0' ],
object = Object.create(null);
array.forEach(function (a) {
var p = a.split('=');
object[p[0]] = isNaN(p[1]) ? p[1] : +p[1];
});
console.log(object);
The solution using Array.prototype.reduce() function:
var arr = [ 'type=A', 'day=45' ],
trans = arr.reduce(function(r, s){
var parts = s.split('=');
r[parts[0]] = isNaN(parts[1]) ? parts[1] : +parts[1];
return r;
}, {});
console.log(trans);
Iterate over each item in the array
Split on =
Add value to object, at key index
var arr = [ 'type=A', 'day=45' ];
var object = {};
for (var i = 0; i < arr.length; i++) {
var currentItem = arr[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
There's probably a million different ways to this, this way uses two different functions. the _.map() call runs on every element, splitting (and parsing) the element (if it matches a character regex). It then uses Lodash's .fromPairs function, which converts an array made up of 2 element arrays to return an object.
var arr = ['type=A', 'day=45'];
var obj = _.fromPairs(_.map(arr, function(item) {
var parts = item.split('=');
var digits = /^\d+$/;
if (digits.test(parts[1])) parts[1] = parseInt(parts[1]);
return parts;
}));
console.log(obj);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Create new array of objects by grouping array of objects based on property value of each object in javascript

I have an array of objects like below, I want to create new array of objects by grouping array of java script objects based on property value of each object in java script
Here I want to group objects based on Group ID and store it into an array of object with unique group ID.
This is my object:
var Object = [
{"Name":15,"GroupID":1,"ComplexObject":1}`object1`
{"Name":16,"GroupID":1,"ComplexObject":1}`object2`
{"Name":17,"GroupID":2,"ComplexObject":2}`object3
{"Name":18,"GroupID":2,"ComplexObject":2}`object4`
{"Name":15,"GroupID":3,"ComplexObject":3}`object5`
{"Name":16,"GroupID":3,"ComplexObject":3}`object6`
{"Name":17,"GroupID":4,"ComplexObject":4}`object7`
{"Name":18,"GroupID":4,"ComplexObject":4}`object8` ];
You can try this way by checking the group id and pushing it to the array object.
var data = [
{"Name":15,"GroupID":1,"ComplexObject":1},
{"Name":16,"GroupID":1,"ComplexObject":1},
{"Name":17,"GroupID":2,"ComplexObject":2},
{"Name":18,"GroupID":2,"ComplexObject":2},
{"Name":15,"GroupID":3,"ComplexObject":3},
{"Name":16,"GroupID":3,"ComplexObject":3},
{"Name":17,"GroupID":4,"ComplexObject":4},
{"Name":18,"GroupID":4,"ComplexObject":4}
];
console.log("Original Data : ", data);
var previousGroupId;
var newObject = new Object();
for(index in data){
var groupId = data[index].GroupID;
if(groupId != previousGroupId){
var newGroup = "GroupId" + groupId;
newObject[newGroup] = new Array();
for(index in data){
if(data[index].GroupID == groupId){
var customObject = {
"GroupID" : groupId,
"Name" : data[index].Name,
"ComplexObject" : data[index].ComplexObject
};
newObject[newGroup].push(customObject);
}
}
}
previousGroupId = groupId;
}
console.log("Grouped data : ", newObject);
jsFiddle
var new_arr = [];
Objects.forEach(function(object) {
if (new_arr.length <= object.GroupID) {
new_arr[object.GroupID] = [];
}
new_arr[object.GroupID].push(object);
});
Update: if you want the length of the array, just use:
var new_arr = [];
Objects.forEach(function(object) {
if (new_arr.length < object.GroupID) {
new_arr[object.GroupID - 1] = [];
}
new_arr[object.GroupID - 1].push(object);
});
and you will get this:

Categories

Resources