Link to home
Start Free TrialLog in
Avatar of lvmllc
lvmllcFlag for United States of America

asked on

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

Avatar of KNVB HK
KNVB HK
Flag of Hong Kong image

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

Avatar of lvmllc

ASKER

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.
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

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

Avatar of lvmllc

ASKER

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

SOLUTION
Avatar of KNVB HK
KNVB HK
Flag of Hong Kong image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lvmllc

ASKER

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

If it works as what you need, you have to give me points.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of lvmllc

ASKER

Sorry on the points, I had started to award it and got side tracked and forgot to come back to finish.
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 :(
Avatar of lvmllc

ASKER

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
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  ;)
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.
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.
Avatar of lvmllc

ASKER

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.
@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...