• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 324
  • Last Modified:

retrieve filtered value out of JS object

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
lvmllc
Asked:
lvmllc
  • 6
  • 6
  • 5
2 Solutions
 
KNVB HKSITOCommented:
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
 
lvmllcAuthor Commented:
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
 
KNVB HKSITOCommented:
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
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
KNVB HKSITOCommented:
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
 
lvmllcAuthor Commented:
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
 
KNVB HKSITOCommented:
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
 
lvmllcAuthor Commented:
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
 
KNVB HKSITOCommented:
If it works as what you need, you have to give me points.
0
 
Chris StanyonCommented:
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
 
lvmllcAuthor Commented:
Sorry on the points, I had started to award it and got side tracked and forgot to come back to finish.
0
 
Chris StanyonCommented:
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
 
lvmllcAuthor Commented:
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
 
Chris StanyonCommented:
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
 
KNVB HKSITOCommented:
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
 
Chris StanyonCommented:
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
 
lvmllcAuthor Commented:
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
 
Chris StanyonCommented:
@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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

  • 6
  • 6
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now