Solved

retrieve filtered value out of JS object

Posted on 2013-12-04
18
273 Views
Last Modified: 2013-12-09
I have an array like this and want to extract the population and abbr for the id I submit.

The background to this project is that I have loaded a geoJSON file containing the geometry of the state and the state ID and name. Next I need to extract various data values from a second file called stateVals. so just being able to get the wpop value for a state ID submitted will get me close to what I want.

var stateVals = [{
    "name": "Iowa",
        "id": "19",
        "abbr": "IA",
        "wpop": "3046355"
}, {
    "name": "North Dakota",
        "id": "38",
        "abbr": "ND",
        "wpop": "6725915"
}, {
    "name": "Minnesota",
        "id": "27",
        "abbr": "MN",
        "wpop": "5303925"
}, {
    "name": "South Dakota",
        "id": "46",
        "abbr": "SD",
        "wpop": "8141805"
}];
console.clear();

var thePop = stateVals.filter(function (bar) {
    console.log(bar.wpop);
    return bar.id == "19"
    // => [{ "name": "Iowa", "id": "19", "abbr": "IA", "wpop": "3046355" }]
});
thePop();

Open in new window

0
Comment
Question by:lvmllc
  • 6
  • 6
  • 5
18 Comments
 
LVL 7

Expert Comment

by:cstsang
ID: 39697302
Hope it can help you:
<html>
	<script language=javascript>
		var stateVals = [{
						    "name": "Iowa",
						        "id": "19",
						        "abbr": "IA",
						        "wpop": "3046355"
						}, {
						    "name": "North Dakota",
						        "id": "38",
						        "abbr": "ND",
						        "wpop": "6725915"
						}, {
						    "name": "Minnesota",
						        "id": "27",
						        "abbr": "MN",
						        "wpop": "5303925"
						}, {
						    "name": "South Dakota",
						        "id": "46",
						        "abbr": "SD",
						        "wpop": "8141805"
						}];
		function builtDropDown()
		{
			var resultDiv=document.getElementById("result");
			for (i=0;i< stateVals.length;i++)
			{
				resultDiv.innerHTML+=stateVals[i].name+"<br>";
			}
	    }
	</script>
	<body onload="builtDropDown()">
		<div id=result>
		</div>
	</body>
</html>

Open in new window

0
 

Author Comment

by:lvmllc
ID: 39697311
Thanks, but I am not trying to build a drop down. I want to access a value from the JSON by providing the criteria to search by.
0
 
LVL 7

Expert Comment

by:cstsang
ID: 39697319
Here is a more advance example:
<html>
	<script language=javascript>
		var stateVals = [{
						    "name": "Iowa",
						        "id": "19",
						        "abbr": "IA",
						        "wpop": "3046355"
						}, {
						    "name": "North Dakota",
						        "id": "38",
						        "abbr": "ND",
						        "wpop": "6725915"
						}, {
						    "name": "Minnesota",
						        "id": "27",
						        "abbr": "MN",
						        "wpop": "5303925"
						}, {
						    "name": "South Dakota",
						        "id": "46",
						        "abbr": "SD",
						        "wpop": "8141805"
						}];
		function builtDropDown()
		{
			var selectObj=document.getElementById("qq");
			selectObj.options.length=stateVals.length;
			for (i=0;i< stateVals.length;i++)
			{
				selectObj.options[i].text=stateVals[i].name;
				selectObj.options[i].value=i;
			}
			retrieve(selectObj);
	    }
	    function retrieve(vv)
	    {
		    var abbrObj=document.getElementById("abbr");
		    var popObj=document.getElementById("pop");
		    var opt=vv.options[vv.selectedIndex].value;
		    var stateVal=stateVals[opt];
		    abbrObj.innerHTML=stateVal.abbr;
		    popObj.innerHTML=stateVal.wpop;
	    }
	</script>
	<body onload="builtDropDown()">
		<table border=1>
			<tr>
				<td><select id=qq onchange="retrieve(this)"></select></td>
				<td>Abbr:</td>
				<td id=abbr></td>
				<td>Population:</td>
				<td id=pop></td>
			</tr>
		</table>		
	</body>
</html>

Open in new window

0
 
LVL 7

Expert Comment

by:cstsang
ID: 39697330
Sorry,I overlook something, you may refer the following code:
var thePop = stateVals.filter(function (bar) {
    console.log(bar.wpop);
    for (i=0;i< stateVals.length;i++)
	{
		if (bar.id==stateVals[i].id)
		{	
			return stateVals[i];
			break;
		}
	}
});

Open in new window

0
 

Author Comment

by:lvmllc
ID: 39697368
Getting close here. In the example below I pass 19 to the function - but how do I get the return value into a variable so I an use it?

lookup = function(x){
var thePop = stateVals.filter(function (bar) {
    //console.log(stateVals.length);
    for (i=0;i< stateVals.length;i++)
	{
		if (bar.id == x)
		{	
			return bar.name;
			break;
		}
	}
});
}
lookup(19);

Open in new window

0
 
LVL 7

Assisted Solution

by:cstsang
cstsang earned 200 total points
ID: 39697381
You may try:
lookup = function(x){
var thePop = stateVals.filter(function (bar) {
    //console.log(stateVals.length);
    for (i=0;i< stateVals.length;i++)
	{
		if (bar.id == x)
		{	
			return bar.name;
			break;
		}
	}
});
 return thePop;
}

Open in new window

0
 

Author Comment

by:lvmllc
ID: 39697411
got it - thanks!

lookup = function (x) {
    var thePop = stateVals.filter(function (bar) {
        //console.log(stateVals.length);
        for (i = 0; i < stateVals.length; i++) {
            if (bar.id == x) {
                //console.log(bar.name)
                return bar.name;
                break;
            }
        }
    });
    return thePop;
}

v = lookup(38)[0].name
console.log(v);

Open in new window

0
 
LVL 7

Expert Comment

by:cstsang
ID: 39697471
If it works as what you need, you have to give me points.
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 200 total points
ID: 39697840
You flagged this as jQuery so there's a much easier way of doing it:

lookup = function(id) {
	return $(stateVals).filter(function() { return ( $(this).attr('id') == id ); });
};

v = lookup(38);
console.log(  v.attr('name')  );
console.log(  v.attr('wpop')  );

//alternatively:
console.log(  lookup(27).attr('name')  );

Open in new window

0
 

Author Comment

by:lvmllc
ID: 39698064
Sorry on the points, I had started to award it and got side tracked and forgot to come back to finish.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39698086
Why use 1 line of code when you can use 11 ;)

The for loop, the if statement and the break in the accepted answer are completely unnecessary...

Code bloat :(
0
 

Author Comment

by:lvmllc
ID: 39698271
Chris,
Your result also works great and I am trying to figure out how to get you points. I just sort of fumbled this one but both of you provided good answers.

Having both is very helpful as I work with students and want them to see multiple methods.

Thanks


cjs
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39699142
Hey cjs,

I'm not overly worried about the points.

What concerns me more is that people will visit this question in the future and assume that the accepted answer is somehow correct! While it works - it's not correct - I could write you a script with a 1000 lines of code that will work, but 999 of them won't actually do anything!

The code that was accepted as an answer shows a complete mis-understanding of the filter() function, and coding methods in general. The reason it works is luck more than judgement.

A lot of the Experts here at EE try to maintain the integrity and high-standard of the answers given, so it's a little frustrating when such a poor answer is accepted. Ultimately it's up to you which answer you accept and who you award the points to - it's your question and your project so you can code it however you like.

A lot of people may now copy and paste that code into their projects, assuming that it's somehow the best way to do it. It's not!!

Rant Over

Pleased you got it working  ;)
0
 
LVL 7

Expert Comment

by:cstsang
ID: 39700002
Hey ChrisStanyon, you need to aware your wording.
You can comment my solution is stupid.
My solution can fulfill the requirement in a stupid way only, so not incorrect.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39700034
I'm well aware of my wording, and I stand by it. It works, but it's not the correct way to use the filter() function. As I said in my previous comment - the fact it works is down to luck more than judgement.
0
 

Author Comment

by:lvmllc
ID: 39700130
Regardless - I appreciate the work you both did to help me - your willingness to provide help is something that I think sets programmers/hackers (whatever you want to call all of this !) apart from so many other professions I deal with.
Thanks.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39700492
@lvmllc - we're always willing to help, and the biggest favour you can do yourself is to understand the code you are given, rather than just copying and pasting. While the copy/paste approach will get the job done (sometimes), you'll often find yourself transferring bad code into your application, which makes the job of debugging extremely difficult. If you understand the code properly, then you can adapt it to your own needs.

Give a man a fish and he eats for a day. Teach a man to fish and eats for a lifetime!

We're always happy to answer questions about any code, so if there's something you don't understand, then just ask.

Just as an example - the code you accepted as an answer has an unnecessary for loop in there, along with an unnecessary if statement. Your test data, stateVars, contains information for 4 states. If it contained all 50 states, then the code would loop through 2500 times, and run the if statement 2500 times!!! It only needs to loop 50 times.

You can see how bad code can quickly mess up your application...
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now