Angular JS copy Object to another into a for loop - javascript

Trying to copy a part of a json object into another json object (thats a filter), into a for loop, under a conditional statement, it doesn't work.
This work but a plain to write an array:
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats.push(
{
"id" :omegaCandidats[i].id,
"prenom" :omegaCandidats[i].prenom,
"nom" :omegaCandidats[i].nom,
"heure" :omegaCandidats[i].heure,
"dateRdv" :omegaCandidats[i].date
}
)
};
};
This doesn't work, and that's what i want to do. Its logical and should work:
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats[i] = omegaCandidats[i];
};
};
This one work but only get one value of the for loop its useless:
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats[0] = omegaCandidats[i];
};
};

what about using a filter:
$scope.candidats = omegaCandidats.filter(function(candidat){
return candidat.dateRdv == date;
});

You can use filter array method, try this:
$scope.candidats = omegaCandidats.filter(function(item) {
return item.dateRdv==date;
});

I think this should work :
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
//$scope.candidats.push(omegaCandidats[i]);
$scope.candidats.push(angular.copy(omegaCandidats[i]));
//copy will create a new reference for your object.
};
};
The code you had is not logical to me :
$scope.candidats=[];
for (i=0;i<omegaCandidats.length;i++){
if (omegaCandidats[i].dateRdv==date){
$scope.candidats[i] = omegaCandidats[i]; // This can't work because $scope.candidats[i] is not defined.
// You would also have an inconsistent array
};
};

Related

JavaScript selecting Object Arraylike?

The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name

How to use options object in Javascript's Function

I am trying this to get input as an argument with some objects,
function write(param) {
var str = param.str;
var elem = param.elem;
document.getElementById(elem).innerHTML= str;
}
and I'm passing this as an argument,
write({
elem:"op",
str:"Hello"
});
The thing I have to do is that I am having font tag with id 'op',
<font id="op"></font>
and when I run this I wont print Hello, as I have given Hello as an object parameter with op element for output.
I'm not sure where exactly your code has gone wrong. Here you can see that both the javascript and the html you produced should work together just fine.
function write(param) {
var str = param.str;
var elem = param.elem;
document.getElementById(elem).innerHTML = str;
}
write({
elem: 'op',
str: 'Hello'
})
<font id="op"></font>
As far as I'm seeing it, your code works as intended.
Answer for using an options object on a function:
In ES6 default parameters can prevent values to be undefined, however it does not actually compensate for the case that you're passing an object with missing parameters.
In this case I would suggest using Object.assign():
function write(options){
options = Object.assign({}, {
myDefaultParam: 'Hello',
elem: null,
str: ''
}, options);
if(options.elem) document.getElementById(options.elem).innerHTML = options.str;
}
What Object.assign() does is to merge a object of default options with the provided functions, allowing you to set default parameters that you can rely on. In this case write({}) would result in options being this object:
{
myDefaultParam: 'Hello',
elem: null,
str: ''
}
If this is overkill for you, I would suggest to simply check wether the keys are defined on your param object like this:
function write(param){
if(!param || !param.elem || !param.str) return false;
return document.getElementById(param.elem).innerHTML = param.str;
}

I need to create a Javascript Function to create custom push function

I am building JavaScript code to make a custom push function. My new function should act exactly like the original push function.
Here is the code. Please check it.
<script type="text/javascript">
function MyArray(){
this.add=function(x){
return this[this.length]=x;
}
}
MyArray.prototype=Array.prototype;
var collection = new MyArray();
collection.push(44);
collection.add(56); // this is not working.
collection.push(77);
collection.push(88);
console.log(collection);
</script>
Because you're not using a native array, the length property doesn't automatically adjust itself. You need to increment it manually, otherwise the next push will just overwrite it:
function MyArray(){
this.add=function(x){
return this[this.length++]=x;
}
}
If you want to use add instead of push (so, use add as push-alias), just refer to the original Array.prototype.push. See snippet. The snippet also contains a custom addMulti method, derived from Array.prototype.push.
function MyArray(){ }
MyArray.prototype = Array.prototype;
MyArray.prototype.add = Array.prototype.push;
// custom addMulti method, derived from Array.prototype.push
MyArray.prototype.addMulti = function addMulti(arrayOfValues){
[].push.apply(this, arrayOfValues);
};
var foo = new MyArray;
// add and push both work
foo.add(13);
foo.push(17);
foo.add(15,16,18);
foo.push(112);
// push an array of values
foo.addMulti([200,300,400,500]);
var report = new MyArray;
report.add('<code>foo.length: ',foo.length, ', foo: [', foo, ']</code>');
document.querySelector('#result').innerHTML = report.join('');
<div id="result"><div>

Better way to build JSON array and retrieve its elements

Here's how I'm initializing and building an array:
var newCountyInfo = new Object();
newCountyInfo.name = newCountyName;
newCountyInfo.state = newCountyState;
newCountyInfo.zips = newCountyZips;
newCountyInfo.branchID = newCountyBranchID;
So I have my four elements in the array. I'm then passing newCountyInfo to another function to pull out the elements for display in some HTML elements.
The only way I know how to get to the individual elements in the function that uses them is this:
JSON.parse(JSON.stringify(newCountyValidation)).name
JSON.parse(JSON.stringify(newCountyValidation)).state
... etc...
There's got to be a better/shorter/more elegant way of doing this!
What is it?
Why are you serializing at all? I don't understand what JSON has to do with this, unless you're using web workers, ajax, or something else which demands serialization. Start with object literal syntax:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
};
And just pass the whole object to the other function:
someOtherFunction(newCountyInfo);
Which can access the fields using plain old property accesses:
function someOtherFunction(foo) {
console.log(foo.name); // whatever was in newCountyname
}
No JSON whatsoever.
Something like this should work just fine:
var newCountyInfo = {
name: newCountyName,
state: newCountyState,
zips: newCountyZips,
branchID: newCountyBranchID
}
function test(newCountyValidation)
{
alert(newCountyValidation.name);
}
test(newCountyInfo);

Dynamically assigning object keys and values with "for"

I have a function, SWFUpload_config, which takes an argument, post_params_arr - an object.
post_params_arr = {"ajaxtask":"swfupload_files", "param": "2012"}
I need to parse that post_params_arr and dynamically add keys and values to swfu_settings in the following way (please notice that swfu_settings has by default 'SWFSESSID' : session_id and all other keys:values must be added from post_params_arr):
function SWFUpload_config (post_params_arr) {
var swfu_settings = {
'SWFSESSID' : session_id,
'ajaxtask' : 'swfupload_files',
'param' : '2012'
};
}
How can I achieve that? How would I parse post_params_arr inside swfu_settings where I am assigning keys and values?
The same way you'd access any other object...
var swfu_settings = {
ajaxtask: post_params_arr.ajaxtask,
param: post_params_arr.param
};
Or do you mean it's JSON? If you have jQuery, parse it using jQuery.parseJSON; otherwise, use JSON.parse and fall back on eval('(' + post_params_arr + ')').
If you need to shallow-clone the object for some reason, a for in loop will work:
var swfu_settings = {
SWFSESSID: 'blah'
// etc.
};
for(var x in post_params_arr) {
if(post_params_arr.hasOwnProperty(x)) {
swfu_settings[x] = post_params_arr[x];
}
}

Categories