javaScript - JSON push() Formatting - javascript

How to push data to JSON variable in below format?
[
"name":"sample name"
,"first_name":"sample first"
,"last_name":"sample last"
,"email":"sample.#mail.com"
]
but what's happening is the below format..
[
{"name":"sample name"}
,{"first_name":"sample first"}
,{"last_name":"sample last"}
,{"email":"sample.#mail.com"}
]
I have to set it that way because I'm using fluentPDO.
Edit:
Below is part of my code...
var r = [];
angular.forEach($scope.fields, function(value, index) {
var f = value.field;
var o = {};
o[f] = $('#'+value.id).val();
r.push(o);
});
return angular.toJson(r);
On the PHP side (the one I call on $.post() method)...
$set = json_decode($_POST["fields"], true)
echo json_encode($set);

You need to create an object not an array of objects so
var r = {};
angular.forEach($scope.fields, function (value, index) {
r[value.field] = $('#' + value.id).val();
});
return angular.toJson(r);

Related

Organize Array Items

I have the following JavaScript array:
var allItems = ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4', 'AAL_NO1', 'AAL_NO2', 'MML_NO1', 'MML_NO2'];
Now I want to sort the array in this format, to put the values in a dropdown:
var sorted = { 'BBL': ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4'],
'AAL': ['AAL_NO1', 'AAL_NO2'],
'MML': ['MML_NO1', 'MML_NO2']};
Does anyone know how I can do that?
You can do it using Array.prototype.reduce() function.
Example:
var allItems = ['BBL_NO1', 'BBL_NO2', 'BBL_N03', 'BBL_NO4', 'AAL_NO1', 'AAL_NO2', 'MML_NO1', 'MML_NO2'];
var sorted = allItems.reduce(function (acc, item) {
var mainPart = item.split('_')[0];
if (!acc.hasOwnProperty(mainPart)) {
acc[mainPart] = [];
}
acc[mainPart].push(item);
return acc;
}, {});
console.log(sorted);

How to get JSON object in array?

var data = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
Here I have posted my JSON data. I want to get all the defaultValue in JSON/Array format. My output should be like-
defaultValues:['Size30','Black','Low']
How to manage that in the foreach loop?
my code :
var otherSelectedOption;
angular.forEach(data, function(optionValue, optionKey) {
if (optionValue.defaultValue.text) {
otherSelectedOption = (optionValue.defaultValue.text);
}
selectedOption = {defaultValues: otherSelectedOption};
console.log(selectedOption);
});
Your JSON is not valid, since objects are not separated by comma ,
Suppose this is the JSON
var obj = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
try
var arr = JSON.parse(obj).map( function(item){
return item.defaultValue;
});

Flattening json such that one property is key and the other value

I have data in following format..
var array = [{"name":"abc","boss":"def","sub":[{"schema":"a","data":1},{"schema":"b","data":0},{"schema":"c","data":0}]},
.
.
.
]
I wish to transform it to the following structure:
[{"name":"abc","boss":"def","a":1,"b":0,"c":0},
.
.
.
]
Based on the answer here.. I tried..
grouped = [];
array.forEach(function (a) {
if (!this[a.name]||!this[a.boss]) {
this[a.name] = { name: a.name, boss:a.boss };
grouped.push(this[a.name]);
}
this[a.name][a.sub.schema] = (this[a.name][a.sub.schema] || 0) + a.sub.data;
}, Object.create(null));
console.log(grouped);
The above gives undefined:NaN as the third property in the result objects..
Any help is sincerely appreciated.
Thanks
You probably want to reduce the sub object to properties of the item.
The following code maps the items in array to a new array, which contains the flattened items:
array = array.map(function(item) {
item = item.sub.reduce(function(x,y) { return x[y.schema] = y.data, x; }, item);
delete item.sub;
return item;
});
Try this simply.
var arr = [];
array.forEach(function(ele){
var obj = {};obj.name=ele.name;
obj.boss=ele.boss;
ele.sub.forEach(function(e){
obj[e.schema] = e.data
});
arr.push(obj)
});

How to convert a JSON object to Javascript array filtered by key?

I'm returning a JSON object from an Ajax request which outputs the following keys and values:
[{"App_Name":"Maccy D's","ID":2017},{"App_Name":"B King","ID":2011}]
I need to convert this object to a Javascript array where each App_Name and ID value is concatenated as one string in the array. So for example:
['Maccy D's 2017', 'B King 2011'] // etc...
What I have tried is calling
var assetsArray = JSON.parse(assetJSON);
but when I bind the assetsArray to a list it shows [object Object] for each menu item. Instead of the intended App_Name + ID concatenation:
How can I convert a JSON object to Javascript array filtered by key?
This is how I bind the JSON returned to the menu list:
Ajax request:
//call an Ajax GET for the asset name data
$.ajax({
url: asset_list_request_url,
cache: false,
success: function(assetJSON){
bindAssetNamesMenu(assetJSON);
}
});
Mapping function:
function bindAssetNamesMenu(assetJSON)
{
var assetsArray = JSON.parse(assetJSON);
$.each(assetsArray, function(i)
{
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(assetMenu);
var a = $('<a>')
.addClass('ui-all')
.appendTo(li);
var input = $('<input/>')
.addClass('ui-all')
.attr('type', 'checkbox')
.appendTo(a);
var span = $('<span>')
.text(assetsArray[i])
.appendTo(a);
});
}
You can use map() to get the array of objects in to an array of the format you require:
var data = [{"App_Name":"Maccy D's","ID":2017},{"App_Name":"B King","ID":2011}]
var arr = data.map(function(obj) {
return obj.App_Name + ' ' + obj.ID;
})
console.log(arr);
Alternatively, you could just work with the array of objects as it is, like this:
$.ajax({
url: asset_list_request_url,
cache: false,
dataType: 'json',
success: bindAssetNamesMenu
});
function bindAssetNamesMenu(arr) {
$.each(arr, function() {
var $li = $('<li/>').addClass('ui-menu-item').attr('role', 'menuitem').appendTo(assetMenu);
var $a = $('<a>').addClass('ui-all').appendTo($li);
var $input = $('<input/>').addClass('ui-all').attr('type', 'checkbox').appendTo($a);
var $span = $('<span>').text(this.App_Name + ' ' + this.ID).appendTo($a);
});
}
you don't need var assetsArray = JSON.parse(assetJSON);
keep your names straight, not assetJSON and assetArray
you have to access the property of the array index, like assetJSON[i].App_Name
Then your code is working fine!
var data = [{
"App_Name": "Maccy D's",
"ID": 2017
}, {
"App_Name": "B King",
"ID": 2011
}];
var assetMenu = $("ul");
bindAssetNamesMenu(data);
function bindAssetNamesMenu(assetJSON) {
$.each(assetJSON, function(i) {
var li = $('<li/>')
.addClass('ui-menu-item')
.attr('role', 'menuitem')
.appendTo(assetMenu);
var a = $('<a>')
.addClass('ui-all')
.appendTo(li);
var input = $('<input/>')
.addClass('ui-all')
.attr('type', 'checkbox')
.appendTo(a);
var span = $('<span>')
.text(assetJSON[i].ID + " - " + assetJSON[i].App_Name)
.appendTo(a);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
If you would like to code in the imperative style then you can always use for of loop such as;
var data = [{"App_Name":"Maccy D's","ID":2017},{"App_Name":"B King","ID":2011}],
datar = [];
for (var object of data) datar.push(object.App_Name + " " + object.ID);
console.log(datar);
You can using jQuery.each function to loop through the json and concatenate the required strings using either concat property (javascript) or directly use +(concatenation operator)
var json = [{"App_Name":"Maccy D's","ID":2017},{"App_Name":"B King","ID":2011}];
var arr = [];
jQuery.each(json,function(){
arr.push(this.App_Name.concat(this.ID))
});
console.log(arr); // This will display ["Maccy D's 2017", "B King 2011"]

Filter properties from an array based on another array

I have an array of objects like this:
var bridges = {"countyCd:15
createdDate:"0001-01-01T00:00:00"
createdUserId:0
createdUserIdZ:null
createdUserName:null
description:"SR 1#.-CENTRAL RR COMP OF IND"
districtId:null
encryptedId1:null
encryptedId2:null
isDirty:false
modelState:null
nbiNumber:10
routeNbr:"1"
routeTypeCd:"SR"
transactionType:null
updatedDate:"0001-01-01T00:00:00"
updatedUserId:0
updatedUserIdZ:null
updatedUserName:null", [...]....}
I have another array like this
[countyCd, nbiNumber]
How can create another array keeping just two properties so it becomes like
bridges = {"countyCd:15
nbiNumber:10"
, [...]....}
Basically, I am looking for a way to create a function that takes a data array and a filter array as parameters and filters the data array based on the filter array.
Any pointers to this will be much appreciated.
One solution would be to map over each record and reduce your filter array into an object containing the target proprties:
var bridges = [{
countyCd:15,
createdDate:"0001-01-01T00:00:00",
createdUserId:0,
createdUserIdZ:null,
createdUserName:null,
description:"SR 1#.-CENTRAL RR COMP OF IND",
districtId:null,
encryptedId1:null,
encryptedId2:null,
isDirty:false,
modelState:null,
nbiNumber:10,
routeNbr:"1",
routeTypeCd:"SR",
transactionType:null,
updatedDate:"0001-01-01T00:00:00",
updatedUserId:0,
updatedUserIdZ:null,
updatedUserName:null
}, {
countyCd:23,
createdDate:"0001-01-01T00:00:00",
createdUserId:0,
createdUserIdZ:null,
createdUserName:null,
description:"SR 1#.-CENTRAL RR COMP OF IND",
districtId:null,
encryptedId1:null,
encryptedId2:null,
isDirty:false,
modelState:null,
nbiNumber:10,
routeNbr:"1",
routeTypeCd:"SR",
transactionType:null,
updatedDate:"0001-01-01T00:00:00",
updatedUserId:0,
updatedUserIdZ:null,
updatedUserName:null
}];
var filters = ['countyCd', 'nbiNumber'];
var transformedRecords = bridges.map(bridge => filters.reduce((p, c) => {
p[c] = bridge[c];
return p;
}, {}));
console.log(transformedRecords);
Say you have an array of bridges, call it bA:
var bA = []; //bridges array
var nbiA = []; // nbia array with countyCd
var newA = []; // new array
bA.forEach(function(element, index, array){
var newEntry = {
'countyCd':element.countyCd,
'nbiNumber':nbiA.find(function(nbi){
return nbi[countyCd] == element.countyCd;
}).nbiNumber
};
newA.push(newEntry);
});
//do whatever you want with the newA array

Categories