So I have an empty array defined.
admin.links = [];
I then push items to it like so.
angular.forEach(links, function(value, key) {
var title = value.title;
var url = value.url;
admin.links.counter.push({
'parent' : counter,
'name' : title,
'url' : url
})
})
When I run the code above I get an error
Cannot read property 'push' of undefined
counter is a dynamic value. How would I do this?
I want it to be something like admin.links.0
What you mean with:
counter is a dynamic value.
admin.linksis an array, so if you want to add items you must use:
admin.links.push
if, instead, you want links to be an object you should initialize it with:
admin.links = {
counter: []
}
admin.links.counter.push()
Related
I don't know what's wrong with the code. it works fine and both array have data. but i don't understand why the output found undefined from var _city array as it passed data to the city field.
How can I fix this?
var city = {
_country : _city
};
I'm wondering what you read that made you possibly believe that by writing what you did you would magically have an object keyed with one array with values from a second...
Essentially what is happening when you did when you
var city = {
_country : _city
};
is create an object that looks like
var city = {
'_country' : ['your', 'array', 'of', 'cities']
};
that is to say, an object with one key, '_country' mapped to an array of cities.
This explains why you get undefined... city['any string that isn't exactly " _country"'] == undefined
What you want to do is more likely,
var city = _country.reduce(function(acc, cur, idx) { acc[cur] = _city[idx]; return acc; }, {});
It's because _country is already defined above:
var _country = ["Afghanistan","Bahrain","Canada","Denmark","Ethiopia","France","Germany","Hong Kong","India","Japan"];
Change the definition within city to something else (maybe country):
var city = {
country: _city,
};
And it'll work.
Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc
I'm creating a very simplified version of a drag and drop shopping cart with jqueryui.
My issue is regarding adding data(id, name, price) to an array.
I tried several methodes of adding the data (also an array) to the main container(array). But I keep getting this error: Uncaught TypeError: undefined is not a function
var data = [];
function addproduct(id,name,price){
//var d = [id,name,price];
data[id]["name"] = name;
data[id]["price"] = price;
data[id]["count"] = data[id]["count"]+1;
console.log(data);
}
the addproduct() function can be called by pressing a button
It is not entirely clear to me what type of data structure you want to end up with after you've added a number of items to the cart. So, this answer is a guess based on what it looks like you're trying to do in your question, but if you show a Javascript literal for what you want the actual structure to look like after there are several items in the cart, we can be sure we make the best recommendation.
You have to initialize a javascript object or array before you can use it. The usual way to do that is to check if it exists and if it does not, then initialize it before assigning to it. And, since you're keeping a count, you also will want to initialize the count.
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id]["name"] = name;
data[id]["price"] = price;
++data[id]["count"];
console.log(data);
}
And FYI, arrays are used for numeric indexes. If you're using property names like "name" and "price" to access properties, you should use an object instead of an array.
And, I would suggest that you use the dot syntax for known property strings:
var data = [];
function addproduct(id,name,price){
if (!data[id]) {
// initialize object and count
data[id] = {count: 0};
}
data[id].name = name;
data[id].price = price;
++data[id].count;
console.log(data);
}
It looks like what you want is an array of objects, although I would need a more detailed description of your problem to be clear.
var data = []
function addproduct(id, name, price)
{
data.push({'id': id, 'name':name, 'price': price, 'count': ++count});
console.log(data);
}
I'm facing an issue with accessing the array element in AngularJS. I have an array:
$scope.salesentry = [
{
sales_id:'',
product_id: '',
product_category_id:'',
sale_qty:null,
sale_amount:null
}
];
I want to update the sales_id field value on some button click like:
$scope.saveData = function() {
$scope.salesentry.sales_id='10';
});
I'm not able to access it in the above way. How can I do so?
salesentry is an array, so you need to access a specific element on it first using [0].
So your code becomes:
$scope.saveData = function() {
$scope.salesentry[0].sales_id='10';
});
Do you want to update each salesentry's sales_id ?
If yes you may use
angular.foreach($scope.salesentry, function(value, key){
value.sales_id = 10;
});
You need to index the array
$scope.salesentry[0].sales_id = '10'
Also, no need for the comma at the end.
I have a cart on my website and I need to let users easily change the quantity of items they have in their cart at a moment.
Here is the javascript code I have so far:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
var items = [];
$(".item").each(function () {
var productKey = $(this).find("input[type='hidden']").val();
var productQuantity = $(this).find("input[type='text']").val();
items.addKey(productKey, productQuantity); ?
});
// 1. Grab the values of each ammount input and it's productId.
// 2. Send this dictionary of key pairs to a JSON action method.
// 3. If results are OK, reload this page.
});
</script>
The comments I wrote are just guidelines for me on how to proceed.
Is there a way to add a key/pair element to an array of sorts? I just need it to have a key and value. Nothing fancy.
I wrote in an addKey() method just for illustrative purposes to show what I want to accomplish.
items[productKey] = productQuantity;
In JavaScript, Arrays are Objects (typeof(new Array)==='object'), and Objects can have properties which can be get/set using dot- or bracket- syntax:
var a = [1,2,3];
JSON.stringify(a); // => "[1,2,3]"
a.foo = 'Foo';
a.foo; // => 'Foo'
a['foo']; // => 'Foo'
JSON.stringify(a); // => "[1,2,3]"
So in your case, you can simply the productQuantity value to the productKey attribute of the item array as such:
items[productKey] = productQuantity;
items[productKey]; // => productQuantity
You can add anonymous objects to the items array like:
items.push({
key: productKey,
quantity: productQuantity
});
Then access them later as items[0].key or items[0].quantity.
Also you can use JQuery.data method and like that you can also get rid of those hidden.