I have this function which takes a json parameter which contains an array of search objects.
function receiveSearch(search, json) {
return {
type: RECEIVE_SCHOOL_SEARCH,
items: json.packages,
receivedAt: Date.now(),
search: Object.assign({}, search, { next: json.next, start: search.next }),
};
}
My json
property looks like:
>0:Object
>1:Object
>2:Object
>3:Object
...{ more }
I would like to return to the search object two properties from json i.e name and suburb. How do I do this? I would prefer to use something neat like lodash/ramda/underscore but plain js is fine.
And each object contains the following properties:
id:"10360"
centreId:776
name:"ABBOTSFORD"
suburb:"TARNEIT"
The easiest solution to you problem using JavaScript could be make a new object which contains only required property and return that.
Just assume your json looks like this:
var x = {search:{id:"10360",centreId:776,name:"ABBOTSFORD",suburb:"TARNEIT"},otherProp:val}
To get required properties, you can make another function and return the object with required fields:
function ReturnRequiredPropertyObject(anyObj)
{
var newObj = {};
newObj.search = {};
newObj.search.name = anyObj.search.name;
newObj.search.suburb = anyObj.search.suburb;
return newObj;
}
You can put the above code in loop if you are getting an array of search object.
To make the above code generic, we can do the following:
function ReturnRequiredPropertyObject(anyObj,requiredPropertyArray)
{
var newObj = {};
for(var counter = 0;counter<requiredPropertyArray.length;counter++)
{
newObj[requiredPropertyArray[counter]] = anyObj[requiredPropertyArray[counter]];
}
return newObj;
}
Hope this will help.
Ok resolved.
Answer is
_.map(json,_.partialRight(_.pick,['name','suburb']));
Related
In the code below, I'm trying to search the JSON output for a specific string (for example 'name_col_lbl') and return its value (in this case 'Name') for AngularJS to ouptut in the view.
$scope.globalContent = [
{"id":"1","module":"student_reg","item":"name_col_lbl","value":"Name"},
{"id":"2","module":"student_reg","item":"bday_col_lbl","value":"Birthdate"}
]
angular.forEach($scope.globalContent, function(el){
$scope.nameLbl = el ***This is where I need to search for the string and return its value***;
$scope.bdayLbl= el ***This is where I need to search for the string and return its value***;
});
I can't seem to find an efficient way to handle this. Thanks in advance!
This should do the trick:
var $scopeglobalContent = [
{"id":"1","module":"student_reg","item":"name_col_lbl","value":"Name"},
{"id":"2","module":"student_reg","item":"bday_col_lbl","value":"Birthdate"}
];
for(var i = 0; i < $scopeglobalContent.length; i++){
for(key in $scopeglobalContent[i]){
if($scopeglobalContent[i][key] == "name_col_lbl"){
return console.log($scopeglobalContent[i].value);
}
}
}
This is basic stuff. I suggest you read on objects and loops to get a better understanding of how this works and how to use it.
From this stackoverflow answer, here's how you can search an array of objects:
var obj = array.filter(function ( obj ) {
return obj.item === "name_col_lbl";
});
obj will contain either the value of name_col_lbl or undefined if the key doesn't exist.
So your code would look like this:
function findObject(array, keyName) {
var obj = array.filter(function ( obj ) {
return obj.item === keyName;
})[0];
return obj;
}
$scope.globalContent = [
{"id":"1","module":"student_reg","item":"name_col_lbl","value":"Name"},
{"id":"2","module":"student_reg","item":"bday_col_lbl","value":"Birthdate"}
]
angular.forEach($scope.globalContent, function(el){
$scope.nameLbl = findObject($scope.globalContent, "name_col_lbl")['value]' ***This is where I need to search for the string and return its value***;
$scope.bdayLbl= findObject($scope.globalContent, "bday_col_lbl")['value]' ***This is where I need to search for the string and return its value***;
});
The findObject function filters the array by returning the first object that it finds where obj.item matches whatever is contained in keyName. This is the obj object which gets returned. Since you don't want the whole object but just a value of that object, I've taken the result of the findObject($scope.globalContent, "name_col_lbl") and added ['value'] which will return just the value key which is what you want to display in the Angular view.
I want to send a multi level array via AJAX. so I tried to make an object of objects as follow:
var info = {};
info.pickup = {};
info.pickup.contact = {};
info.pickup.items_quantity = {};
info.pickup.items = {};
info.delivery = {};
info.delivery.contact = {};
info.delivery.level = {};
then I started filling the objects, for example:
$('.operation-create .pickup .contact-details').each(function () {
var arr = {};
arr['contact_name'] = $(this).find('input[name="pickup-contact-name"]').val();
arr['contact_phone'] = $(this).find('input[name="pickup-contact-phone"]').val();
arr['pickup-suburb'] = $(this).find('select[name="pickup-suburb"]').val();
arr['single-pickup-address'] = $(this).find('input[name="single-pickup-address"]').val();
info.pickup.contact.push(arr);
});
info.pickup.push(info.pickup.contact);
etc...
However unfortunately it didn't work. I get this error:
info.pickup.contact.push is not a function
What I should do here? What is the right way to send this array via AJAX?
You need an array as value
info.delivery.contact = [];
// ^^
The last line
info.pickup.push(info.pickup.contact);
makes no sense, because you have properties in this object. For pushing some values, you need an array
info.pickup = [];
// ^^
An while you already have an array for info.pickup.contact, you could skip the line
info.pickup.push(info.pickup.contact);
It's important to understand the difference between an object and an array.
{} creates a plain object, which doesn't have a push method.
[] creates an array, which is an object with additional features, including a push method.
Looking at your code, at the least, you want info.pickup.contact and probably info.delivery.contact to be arrays (I'm guessing probably items_quantity and items as well, but it's hard to be sure). (The thing you call arr in your looping function isn't an array and doesn't need to be.)
So at a minimum:
info.pickup.contact = [];
// -------------------^^
and
info.delivery.contact = [];
// ---------------------^^
You also want to remove the info.pickup.push(info.pickup.contact); at the end; info.pickup isn't an array, and you've already put the contacts in info.pickup.contact.
Side note: Your code might also benefit from using object initializers:
var info = {
pickup: {
contact: [],
items_quantity: {}, // This might also want to be an array
items: {} // This might also want to be an array
},
delivery: {
contact: [],
level: {} // No idea what you're doing with this, so...
}
};
$('.operation-create .pickup .contact-details').each(function () {
info.pickup.contact.push({
contact_name: $(this).find('input[name="pickup-contact-name"]').val(),
contact_phone: $(this).find('input[name="pickup-contact-phone"]').val(),
pickup-suburb: $(this).find('select[name="pickup-suburb"]').val(),
single-pickup-address: $(this).find('input[name="single-pickup-address"]').val()
});
});
...but it's a matter of style.
info.pickup.contact = {};
That is an object declaration, not array.
An array should be
info.pickup.contact = []; // `[]`
As the other answers have stated you need to change the contact from an object (ie. {}) to an array ([]).
Also note that you can use jQuery's map() to build the array and make the code a little more succinct:
info.pickup.contact = $('.operation-create .pickup .contact-details').map(function () {
return {
contact_name: $(this).find('input[name="pickup-contact-name"]').val(),
contact_phone: $(this).find('input[name="pickup-contact-phone"]').val(),
pickup-suburb: $(this).find('select[name="pickup-suburb"]').val(),
single-pickup-address: $(this).find('input[name="single-pickup-address"]').val()
}
}).get();
You need an array in order to push a element into it. Here it is object so obviously it is not possible for you to add.
if you want to add then make it as array like
info.pickup.contact = [];
now if you add then it will accept. After adding, your array will be like follows..
info.pickup.contact = [];
info.pickup.contact.push("Sample");
{"pickup":{"contact":["Sample"]}}
im currently working on a project that uses javascript as it's front end and im having a bit trouble on adding a key on my existing array.
i have an object that i wanted to be converted on array javascript.
here is my code on how to convert my object to array.
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) { return obj[key]; });
var site_key = $.map( obj, function( value, key ) {
return key;
});
the site_value has the value of my objects.
the site_key has the key.
i want to add my site_key to the site_value array as a Key.
example data:
site_value:
0:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
site_key:
Array[49]
0:"AGB"
1:"BAK"
2:"BAN"
3:"BAR"
i want my array to be
AGB:Array[4]
0:Array[4]
1:Array[1]
2:Array[1]
3:Array[0]
Update:
Here is my object.
Array[1]0:
Object
AGB: Array[4]
BAK: Array[4]
BAN: Array[4]
etc.
You have almost done it and I have modified it a bit below to return it as array object,
var obj = data[0];
var site_value = Object.keys(obj).map(function (key) {
var output = {};
output[key] = obj[key];
return output;
});
I might be misunderstanding the question, sorry if I am. I think you would like to use a key "AGB" instead of an integer for an array index. In this case, you would probably be better served to use an object instead of an array. Maybe something like this
var myObject = {
AGB: Array[4],
AGBarrays: [Array[4],Array[1],Array[1],Array[0]]
};
Then you could access AGB by key and your additional arrays by index
I got a very common question but with a twist which is the reason for this post:
I want to create a key,value object from a string.
my string looks like this:
01§§foo§§bar§§someLink
(i can change the delimiter symbols to whatever i want, if there should be somehow a very tight solution with a specific symbol)
now, i want a key value object and most questions about this problem already got the datapair in the string,(like "id:01,title:foo") but thats not the case in my problem.
i want to generate something like this:
var modules = [
{"ID":"01", "title":"foo", "description":"bar","link":"someLink"},
//more entries from more strings
];
the reason for the key,value object is, that there are more of these strings which I convert from a database. I want it to be in a key,value object so its easier to work with the data later in my tool.
Thank you in advance
You could use Array#split for the string and an array for the keys.
var string = '01§§foo§§bar§§someLink',
moduleKeys = ["ID", "title", "description", "link"],
object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
console.log(object);
A methode for multiple strings.
function getData(array) {
var moduleKeys = ["ID", "title", "description", "link"];
return array.map(function (string) {
var object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
return object;
});
}
var strings = ['01§§foo§§bar§§someLink', '02§§foo§§bar§§someLink'];
console.log(getData(strings));
This should be pretty easy but I'm a little confused here. I want to fill this object:
var obj = { 2:some1, 14:some2, three:some3, XX:some4, five:some5 };
but in the start I have this:
var obj = {};
I´m making a for but I don't know how to add, I was using push(), but is not working. Any help?
You can't .push() into a javascript OBJECT, since it uses custom keys instead of index. The way of doing this is pretty much like this:
var obj = {};
for (var k = 0; k<10; k++) {
obj['customkey'+k] = 'some'+k;
}
This would return:
obj {
customkey0 : 'some0',
customkey1 : 'some1',
customkey2 : 'some2',
...
}
Keep in mind, an array: ['some1','some2'] is basicly like and object:
{
0 : 'some1',
1 : 'some2'
}
Where an object replaces the "index" (0,1,etc) by a STRING key.
Hope this helps.
push() is for use in arrays, but you're creating a object.
You can add properties to an object in a few different ways:
obj.one = some1;
or
obj['one'] = some1;
I would write a simple function like this:
function pushVal(obj, value) {
var index = Object.size(obj);
//index is modified to be a string.
obj[index] = value;
}
Then in your code, when you want to add values to an object you can simply call:
for(var i=0; i<someArray.length; i++) {
pushVal(obj, someArray[i]);
}
For info on the size function I used, see here. Note, it is possible to use the index from the for loop, however, if you wanted to add multiple arrays to this one object, my method prevents conflicting indices.
EDIT
Seeing that you changed your keys in your questions example, in order to create the object, you can use the following:
function pushVal(obj, value, key) {
//index is modified to be a string.
obj[key] = value;
}
or
obj[key] = value;
I'm not sure how you determine your key value, so without that information, I can't write a solution to recreate the object, (as is, they appear random).