Getting access to array inside an object property - javascript

I have an object that I need to iterate through and it is built like this:
points[m] = {
coordinate1: 34,
coordinate2: 23,
code: ["LEM"],
location: '123 fake street'
}
If the current point(point[m]) matches another point I want to add the points[m].code to the point that it matched to build a unique array of objects like this:
pointsUnique[l].code.push(point[m].code[0]);
This works fine, except that when I try and iterate through (pointsUnique[l].code) like this:
for(var n=0;n<pointsUnique[l].code.length;n++){
var codeList = pointsUnique[l].code[n];
console.log(codeList);
}
I only get the 1 result in the code array because (pointsUnique[l].code.length) is apparently 1. Although it has 15 items in it when I view it in the console.
Any assistance on how I could access to all of the values of (pointsUnique[l].code) would be greatly appreciated.

Your logic looks good to me, so something else is probably going on. Are you copy/pasting your real code? For one, you've got a typo here:
pointsUnique[l].code.push(point[m].code[0]);
It should be points[m] not point[m].
Also, what is this mysterious l variable? It could be a problem with that, too, though there's no way of knowing from the code you've posted.

Related

What is the best way to itterate over key value pairs nested in an index using javascript?

I am trying to sort sets of associated key value pairs. They look like this:
{"word":"a","votes":9326,"userMade":"FALSE","limiter":"FALSE"},
But organized into labeled subsets of preferably a string or perhaps an index if necessary.
The data-set is a vote-per-use table of most used english words being parsed into pages.
I will be appending them as text to other html elements due to the constraints my use case, makes it a bit tricky, however, for an example I could work with a simple console.log of the page value followed by the console.log of every word value stored within that page. I need the order preserved. so probably indexed. I will also need to be able to sort each page by the votes value, but I think I can figure the rest out for that.
I have found tutorials on how to search through key-value pairs, but I cannot find how to do all of the following with one solution:
A: access the value of word
B: maintain the order of the data-set, allowing me to append them to the matching html element
C: allows me the opportunity to change which set of elements I am appending to when i have finished looping through a single member of the parent index (the one recording the page)
I imagine it is some combination of for/of and for/in, but I'm getting a headache. Please help?
addl info:
function would run at app startup or when the dataset being examined is changed.
function would take a large dataset filled with around 200 page number values, each with 60+ sets of data like the one listed above, the contents of a single page index for example:
{"word":"a","votes":9326,"userMade":"FALSE","limiter":"FALSE"},
{"word":"aaron","votes":4129,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abandoned","votes":1289,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abc","votes":5449,"userMade":"FALSE","limiter":"FALSE"},
{"word":"aberdeen","votes":641,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abilities","votes":2210,"userMade":"FALSE","limiter":"FALSE"},
{"word":"ability","votes":7838,"userMade":"FALSE","limiter":"FALSE"},
{"word":"able","votes":8649,"userMade":"FALSE","limiter":"FALSE"},
{"word":"aboriginal","votes":1837,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abortion","votes":3232,"userMade":"FALSE","limiter":"FALSE"},
{"word":"about","votes":9295,"userMade":"FALSE","limiter":"FALSE"},
{"word":"above","votes":8818,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abraham","votes":867,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abroad","votes":4969,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abs","votes":2415,"userMade":"FALSE","limiter":"FALSE"},
{"word":"absence","votes":4934,"userMade":"FALSE","limiter":"FALSE"},
{"word":"absent","votes":2937,"userMade":"FALSE","limiter":"FALSE"},
{"word":"absolute","votes":5251,"userMade":"FALSE","limiter":"FALSE"},
{"word":"absolutely","votes":5936,"userMade":"FALSE","limiter":"FALSE"},
{"word":"absorption","votes":285,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abstract","votes":7946,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abstracts","votes":1907,"userMade":"FALSE","limiter":"FALSE"},
{"word":"abuse","votes":7238,"userMade":"FALSE","limiter":"FALSE"},
{"word":"academic","votes":7917,"userMade":"FALSE","limiter":"FALSE"},
{"word":"academics","votes":1706,"userMade":"FALSE","limiter":"FALSE"},
{"word":"academy","votes":6755,"userMade":"FALSE","limiter":"FALSE"},
{"word":"acc","votes":6469,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accent","votes":1020,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accept","votes":7547,"userMade":"FALSE","limiter":"FALSE"},
{"word":"acceptable","votes":4907,"userMade":"FALSE","limiter":"FALSE"},
{"word":"acceptance","votes":7273,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accepted","votes":7684,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accepting","votes":1789,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accepts","votes":1535,"userMade":"FALSE","limiter":"FALSE"},
{"word":"access","votes":9031,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accessed","votes":2932,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accessibility","votes":5702,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accessible","votes":5662,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accessing","votes":2096,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accessories","votes":8875,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accessory","votes":5661,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accident","votes":5664,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accidents","votes":2991,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accommodate","votes":1807,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accommodation","votes":8059,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accommodations","votes":3885,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accompanied","votes":2532,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accompanying","votes":664,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accomplish","votes":1070,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accomplished","votes":2419,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accordance","votes":6434,"userMade":"FALSE","limiter":"FALSE"},
{"word":"according","votes":8282,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accordingly","votes":3003,"userMade":"FALSE","limiter":"FALSE"},
{"word":"account","votes":8996,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accountability","votes":3029,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accounting","votes":7459,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accounts","votes":7507,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accreditation","votes":1605,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accredited","votes":3027,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accuracy","votes":6779,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accurate","votes":6427,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accurately","votes":1493,"userMade":"FALSE","limiter":"FALSE"},
{"word":"accused","votes":2853,"userMade":"FALSE","limiter":"FALSE"},
{"word":"acdbentity","votes":1389,"userMade":"FALSE","limiter":"FALSE"},
and the output would ultimately append the value paired with each word to a specific button through iteration, but also sorted by the page value.
each page is a set of buttons in a 3d object that looks like this:
the text is appended to each button which in turn is a 3d object embeded in an html object using aframe. I can make the appending code.
You can use Object.entries() to get the key value pairs of an object.
var words = [
{"word":"a","votes":9326,"userMade":"FALSE","limiter":"FALSE"},
{"word":"aaron","votes":4129,"userMade":"FALSE","limiter":"FALSE"}
];
words.forEach((wordEntry) => {
var keyValuePairs = Object.entries(wordEntry);
keyValuePairs.forEach((kv) => {
console.log(`key: ${kv[0]} value: ${kv[1]}`);
});
});
my latest attempt looks like this:
for (let p=1; p<129; p++){
for (let b=1; b<68; b++){
let pTpl = (p).toLocaleString(undefined, {minimumIntegerDigits: 3});
let bDbl = (b).toLocaleString(undefined, {minimumIntegerDigits: 2});
var `#fCont${pTpl}${bDbl}` = document.createElement('a-text');
`fCont${pTpl}${bDbl}`.setAttribute('value', 'engWordLib[p,b,0]');
`fCont${pTpl}${bDbl}`.setAttribute('votes', 'engWordLib[p,b,1]');
`fCont${pTpl}${bDbl}`.setAttribute('userMade', 'engWordLib[p,b,2]');
`fCont${pTpl}${bDbl}`.setAttribute('limiter', 'engWordLib[p,b,3]');
`fCont${pTpl}${bDbl}`.setAttribute('visible', 'false');
`fBtn${bDbl}`.appendChild(`#fCont${pTpl}${bDbl}`)
}
}
please note that I havent checked this for errors. I still think this code is to WET and I would prefer the key names for the properties be preserved in the datastructure rather than tacked on when it's appended to the page. I guess I could add a dimension to the array.... seems kind of messy when an object property value has the key value pairs right in it. cant get the iteration of objects in an array down though.... Will continue to persue a cleaner method.

Separate objects in an array from their index using localstorage

I am looking for a way to separate objects from an array, having only the index avaiable. I have something like this:
var hello= [];
for (var i=0; incr.lenght>0; i++;)
{
hello+= originalarray[incr[i]].item;
}
Array:
0: item0
1: item1
2: item2
3: item3
Having this: hello+= originalarray[incr[0,2,3]].item;
I get this: item0item2item3
The "item" comes from another array, this is a small part of my code, but hopefully it's enough to explain my problem.
When I create an alert(hello); what I get is a list of item like this: item0item1item2item3. What I am looking for is a way to separate them. But I need to use the localStorage as well, and I was thinking of creating a different key for every value of the index. Hope it makes sense, I am a new user. Thank you very much!
First of all, the for loop you have in your question has several issues:
It has three ;, while the syntax only allows two. You need to remove the final one
It has a condition that is never true, because lenght has a spelling mistake. If you correct it it will always be true (infinite loop):
incr.length>0
This should be:
i < incr.length
Then the main issue is that you apply a string operator (+=) to concatenate the items, and so hello is no longer an array, but a string:
hello+= originalarray[incr[i]].item;
Instead you should use push:
hello.push(originalarray[incr[i]].item);
In order to store hello in localStorage you should not try to make a key for each item and store each separately. Instead use JSON.stringify (for writing) and JSON.parse (for reading) as explained in this Q&A.

Cannot reorder an array of objects in JS

I have an array of objects which are presented to the user as blocks. They can drag and drop to change the order that that blocks appear, which I then want to change the position of the objects in the array.
$scope.myArray = [{a:1,b:2,c:3}, {a:11,b:22,c:33}, {a:111,b:222,c:333}];
function orderChanged(event) {
console.log($scope.myArray);
//logs [{a:1,b:2,c:3}, {a:11,b:22,c:33}, {a:111,b:222,c:333}]
console.log("source:", event.source.index, "dest:", event.dest.index);
//logs source: 1 dest: 2
$scope.myArray.move(event.source.index, event.dest.index);
console.log($scope.myArray);
//logs [{a:1,b:2,c:3}, {a:11,b:22,c:33}, {a:111,b:222,c:333}]
};
//this is going to rearrange the array
Array.prototype.move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
The orderChange event has the source index and destination index as integers that represent their order as present to the user, which also maps to their positions in the array before any moving has occurred.
I cannot get the array to rearrange, each time I log the array in the orderChange function both logs return the same order.
All of the other examples of array re-ordering are for arrays that do not contain objects, I'm wondering if this is what is messing up my code?
I'm testing your code and works ok. Where are you modifying the Array prototype? Just try to replace the call to move() with the code that actually does the reorder and test...
Anyway, you're using AngularJS. Why are you messing with the DOM? Add a property called Order to each of your objects and let Angular do the syncrhonisation... that what is meant for.
In short, take a look at this module, maybe it would do your life easier:
http://ngmodules.org/modules/ng-sortable
I think, your code works ok, but the log does not.
console.log might not represent the values at runtime, but at viewtime, especially with multidimensional objects and arrays.
Try a different log to see console.log($scope[0].a, $scope[1].a, $scope[2].a)
You might want to check in a different brwoser, as this seems to be a Chrome issue, see here:
Is Chrome's JavaScript console lazy about evaluating arrays?
Wrong value in console.log

Array length issue in azure mobile services

I'm sending an array to the service
[
{
"toppingid": "ABB934CB-EAB7-4863-B832-7F533DA08E2F",
"toppingname": "Default",
"toppingprice": "0.000000"
}
]
When I console.log it shows as above. I do console.log as below
toppinglistforCart = [];
toppinglistforCart = request.body.toppinglist
console.log(toppinglistforCart);
But when I try to toppinglistforCart.length it returns 132 for some peculier reason.
and if I do console.log(toppinglistforCart[0]) then it returns [ very strange. Did someone else came through this same issue?
Thanks for your time
Your toppinglistforCart variable appears to be a string, with length 132. (It doesn't work in older IE, but) JS lets you use the topplinglistforCart[0] syntax to access individual characters within the string, similar to how the same syntax on an array accesses individual array items.
You need to parse the JSON content of your string to create an object:
toppinglistforCart = JSON.parse(request.body.toppinglist);
Note also that your first line:
toppinglistforCart = [];
...is not needed at all - it sets toppinglistforCart to a new empty array but then the next line sets toppinglistforCart to something else so that empty array gets thrown away.

How to find data from array in mongodb

I have collection like this:
{
"name":"silver",
mywants:[
{"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(5878784dfd5d),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(5454dfd44545),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(541dfee88245),mark:{"english":100,"math":100,"science":100}},
]
}
I want to find that given objid is exist in mywants array or not. Then if exist that objid i want that exist object id document to my callback function so i have tried like this
collection.find("{"name":"silver"},{"mywants._id":objid}).toArray(function(err,res)
{
console.log(JSON.stringify(res));
})
But, I got output like
[{"Mywant":[{"_id":"5128b9bc046802720b000003"},
{"_id":"5128c190046802720b000004"},
{"_id":"5128c359175e1aa80b000001"}],"_id":"5128b71455e4e0540b000002"}
]
But i want like this
{"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}}`,
How to find?
You have to call
collection.find({"name":"silver", "mywants._id":objid}).toArray(…)
instead of
collection.find({"name":"silver"},{"mywants._id":objid}).toArray(…)
. The former one represents a query with two expressions ("name":"silver" AND "mywants._id":objid) while the latter one is one expression ("name":"silver") and one projection ("mywants._id":objid) [controls the fields to return]. More info at http://docs.mongodb.org/manual/reference/method/db.collection.find/.
You have typo in your code, it is not ver clear what youwant. Based on your sample with typo and output you want (again with typo) I assume this is what you meant:
-You are doing a find on name:"silver" and want back mywants._id field (has typo) with that syntax.
Instead I assume you meant to find:
name:"silver" AND "mywants._id" : someSpecificId
and output corresponding mywants entry:
db.collection.find({"name":"silver","mywants._id":objid}, {"mywants.$":1, _id:0}).pretty()

Categories

Resources