I have a array in my controller Which has assign multiple keys with the value i need to access these values in controller so that i can save these data to database
Array is given below:-
$scope.Notes['surfacedefault-1'] = { value: "xyz" };
$scope.Notes['surfacedefault-2'] = { value: "we" };
$scope.Notes['surfacedefault-3'] = { value: "123" };
$scope.Notes['surfacedefault-4'] = { value: "red" };
$scope.Notes['surfacedefault-5'] = { value: "blue" };
Please suggest me to access their value in controller using foreach loop
It should be like this
angular.forEach($scope.Notes, function(value, key) {
console.log(key + ': ' + value);
});
Also you can make use of .push to create key value pairs in array, eg:
$scope.Notes.push({'surfacedefault-1':'xyz'});
use forEach in angular
angular.forEach($scope.Notes, function (val, key) {
console.log(val.value)
})
DEMO
that could be a solution?
$scope.Notes=[
{name:'surfacedefault-1', value: "xyz" },
{name:'surfacedefault-2', value: "we" },
{name:'surfacedefault-3', value:"123" },
{name:'surfacedefault-4',value: "red" },
{name:'surfacedefault-5',value: "blue" }];
for(var i=0;i<$scope.notes.length;i++{
do something
}
Use this.
var array = Object.keys($scope.Notes).map(function(key, index, array){
return $scope.Notes[key].value
})
Related
components: any = [
{
id: "17:12610",
name: "custom-component",
hasWarning: true,
selectableKey: 'id',
preview: 'thumbnailLink',
children: {
"17:12610": {
"name": "cc-1",
"type": "instance",
"children": {
"7:43": {
"name": "icon-slot",
"children": {},
"type": "div"
}
}
}
}
}
];
Object.keys(this.components[0].children).forEach((res) => {
console.log(res);
});
I am iterating like this but its only giving me the first ID.
I want to get each children ID & Name. Also I want to track the index so that I can make changes on particular index
I want the output like this:
id: 17:12610
name: cc-1
id: 7:43
name: icon-slot
let child = components[0].children;
while (child) {
const id = Object.keys(child)[0];
const name = child[id].name;
console.log('id: ' + id + ' name: ' + name);
child = child[id].children;
}
You are specifying components[0] before your forEach function. If you have multiple elements in your components array then you will need something like:
(this.components).forEach((root => {
(root.children).forEach((child) => {
console.log('id:' + child + ' name:' + child.name);
}
}
);
Also, looking at your array construction, you have created an array of objects, not an array of key value pairs and so they will not have a key associated with them. If you want keys associated with them, change your object {} to a nested array [].
You edited your question to add the desired output format. I edited my answer accordingly.
You can create a recursive function to achieve the solution. Something like this:
const component = [{"id":"17:12610","name":"custom-component","hasWarning":true,"selectableKey":"id","preview":"thumbnailLink","children":{"17:12610":{"name":"cc-1","type":"instance","children":{"7:43":{"name":"icon-slot","children":{},"type":"div"}}}}}];
const recursive = (arr, formedArr=[]) => arr.reduce((a,e)=>{
Object.entries(e.children || e).forEach(([id, {name, children}])=>{
a.push({id, name});
if(children) recursive([children], a);
});
return a;
},formedArr);
console.log(recursive(component));
So my call returns something like:
data:
{
nameData: 'Test33333',
emailData: email#email.com,
urlLink: link.com
additionalDetails: [
{
field: 'email',
value: 'other#email.com'
},
{
field: 'name',
value: 'name1223'
}
]
}
Now, I want to make a function that would take the passed parameter (data) and make an array of objects, that should look like below. It should be done in more generic way.
Array output expectation:
fullData = [
{
name: 'data_name'
value: 'Test33333'
},
{
name: 'data_email',
value: 'email#email.com'
},
{
name: 'data_url',
value: 'Link.com'
},
extraData: [
//we never know which one will it return
]
];
It should be done in the function, with name, for example:
generateDataFromObj(data)
so
generateDataArrFromObj = (data) => {
//logic here that will map correctly the data
}
How can this be achieved? I am not really proficient with JavaScript, thanks.
Assuming that you keep your data property keys in camelCase this will work for any data you add, not just the data in the example. Here I've used planetLink. It reduces over the object keys using an initial empty array), extracts the new key name from the existing property key, and concatenates each new object to the returned array.
const data = { nameData: 'Test33333', emailData: 'email#email.com', planetLink: 'Mars' };
function generateDataArrFromObj(data) {
const regex = /([a-z]+)[A-Z]/;
// `reduce` over the object keys
return Object.keys(data).reduce((acc, c) => {
// match against the lowercase part of the key value
// and create the new key name `data_x`
const key = `data_${c.match(regex)[1]}`;
return acc.concat({ name: key, value: data[c] });
}, []);
}
console.log(generateDataArrFromObj(data));
Just run a map over the object keys, this will return an array populated by each item, then in the func map runs over each item, build an object like so:
Object.keys(myObj).map(key => {return {name: key, value: myObj[key]}})
I am trying to create a generic function where you are able to pass an object that has a property of a random function. With this you should be able to set a property stating the key and value for each parameter of the function.
the generic function should then call this "random" function with all the parameters.
However im not quite sure how to do it?
// Keep in mind its created for demonstration purposes
var functionOne = function(id)
{
return id;
}
var functionTwo = function(id,name)
{
return id + ' 'name;
}
var functionThree = funciton(id,name,age)
{
return id + ' '+name+' '+age;
}
var obj = [
{
callback: functionOne,
callbackParameters: [{key: 'id', value: 1}]
},
{
callback: functionTwo,
callbackParameters: [{key: 'id', value: 1}, {key: 'name', value:'Marc'}]
},
{
callback: functionThree,
callbackParameters: [{key: 'id', value: 1}, {key: 'name', value: 'Marc'}, {key: 'age', value: 45}]
}
]
obj.forEach(function(x){
//How do i call it with the correct keys? :(
})
Fiddle
You can call apply() on a function in JS and pass an array of parameters into it. So you could use the following assuming your callbackParameters are always in the correct order.
obj.forEach(function(x){
var parameters = x.callbackParameters.map(function(p) { return p.value; });
console.log(x.callback.apply(this, parameters));
})
Updated fiddle https://jsfiddle.net/y6oh1078/1/
Edit: Further reading
If you are interested in more ways to manipulate functions in JS, the following article on currying is a good read - https://www.sitepoint.com/currying-in-functional-javascript/
You cannot do this. This would require something like reflection, i.e. forEach anonymous function should know the definition of every callback function and get names (and what is much more important - order) of its arguments.
However, you can do the following:
var functionOne = function (o) {
return o.id;
};
var functionTwo = function (o) {
return o.id + ' ' + o.name;
};
var functionThree = function (o) {
return o.id + ' ' + o.name + ' ' + o.age;
};
var obj = [{
callback : functionOne,
callbackParameters : [{
key : 'id',
value : 1
}
]
}, {
callback : functionTwo,
callbackParameters : [{
key : 'id',
value : 1
}, {
key : 'name',
value : 'Marc'
}
]
}, {
callback : functionThree,
callbackParameters : [{
key : 'id',
value : 1
}, {
key : 'name',
value : 'Marc'
}, {
key : 'age',
value : 45
}
]
}
];
// Now, are you able to generate `o` objects dynamically using something like:
obj.forEach(function (x) {
var o = {};
x.callbackParameters.forEach(function (p) {
o[p.key] = p.value;
});
console.log(x.callback(o));
});
P.S. Actually, you can dynamically get the names and order of function arguments, but you do not want to do this.
If you are still interested in this, read this question.
I have an array of cars like this:
[{ name:"Toyota Minivan", id:"506" }, { name:"Honda Civic", id:"619" }]
I am trying to check whether the array contains a certain id.
I have tried
var x =!!_.where(cars, {id:'506'}).length;
expecting it to return true if the array contains the id, but it always returns false.
What am I doing here ?
Btw, I don't have to use underscore.js if there is a better way of doing this.
thanks
Thomas
Your code does work (once you fix the syntax errors in the object array):
http://jsfiddle.net/ArPCa/
var cars = [{ name:"Toyota Minivan", id:"506"}, { name:"Honda Civic", id:"619"}];
var x =!!_.where(cars, {id:'506'}).length;
console.log('value: ' + x);
returns "value: true". So there must be a problem somewhere else.
But, a better way to do this might be some:
var y = _.some(cars, function(c) {
return c.id == '506';
});
I know this is late, but even easier:
var cars = [{ name:"Toyota Minivan", id:"506"}, { name:"Honda Civic", id:"619"}];
function findById(id) {
return _.contains(_.pluck(cars, 'id'), id);
}
Say you have the array arr, and your id, id.
arr.filter(function(elem) { return elem.id == id; });
will return an array with the matching element(s);
You could wrap it in a function like:
function findById(arr, id) {
var filtered = arr.filter(function(elem) { return elem.id == id; });
return filtered && filtered.length ? filtered[0] : null;
}
, potentially doing some other stuff if you weren't happy with the default filtered array.
var obj = [{
name: "Toyota Minivan",
id: "506"
}, {
name: "Honda Civic",
id: "619"
}];
function findCar(id) {
return obj.filter(function (car) {
if (car.id == id) {
return car;
}
});
}
self.resultList.forEach(function(item, index, enumerable){
console.log(self.resultList);
item.id=11;
item.get('id');
});
the item like this:
if item.id = 11;
the exception like this:
Assertion failed: You must use Ember.set() to access this property (of
[object Object])
so item.get('id') or item.set('id',11)
the exception like this
Uncaught TypeError: Object # has no method 'get'
is this item not the Ember's Object?so what the item is?
could someone tell me how to change the 'itme.id's value..
Thanks a million
You can use the Ember.set(yourObject, propertyName, value); and Ember.get(yourObject, propertyName); to safely set and get properties.
In your case:
self.resultList.forEach(function(item, index, enumerable) {
Ember.set(item, "id", 11);
Ember.get(item, "id");
});
In my case I did it in this way
//In my controller I've defined the array
displayInfoCheckboxes: [
{
turnover: {
label: "Turnover",
value: 1,
propertyName: "turnover"
}
}, {
pl: {
label: "P&L",
value: 1
}
}
]
//and in my handler I passed the full string path to the property in the set method
let displayInfoCheckboxes = this.get('displayInfoCheckboxes');
let controller = this;
displayInfoCheckboxes.forEach(function(items,index) {
for (var key in items) {
controller.set('displayInfoCheckboxes.' + index + '.' + key + '.value', false);
}
})