0

For a project I have data stored in XML like this:

<xml>
    <sprites>
        <sprite>
            <name>Tile1</name>
            <lat>1</lat>
            <lng>2</lng>
        </sprite>
        <sprite>
            <name>Tile2</name>
            <lat>3</lat>
            <lng>4</lng>
        </sprite>
    </sprites>
<xml>

Through jQuery I want to get a tile object that matches two child values, the lat and lng values.

I found this post which was of great help, but sadly it only has an example of how to search for one matching value. Here's the code I have up to now:

// xml stored in 'xml' var

var findLat = 3;
var findLng = 4;

var mapSprites = $(xml).find("sprites");

var getSprite = $(mapSprites).find("sprite").filter(
    function() {
        return $(this).find('lat').text() == findLat;
    },
    function() {
        return $(this).find('lng').text() == findLng;
    }
);

Sadly getSprite is undefined, as I'm guessing you can't use the filter function as I've tried to use it? The example I linked to has one function as filter and seems to work, but comma separating doesn't seem to work as an AND, which is what I need.

The goal is to be able to give the function a lat and lng value and me being able to extract the <name> value.

Would be thankful for a push in the right direction, I'm pretty new to XML and parsing it through jQuery.

2
  • 1
    problem is filter does not take two arguments like that.... Commented May 23, 2019 at 18:00
  • One function to filter, return (condition1 && condition2) Commented May 23, 2019 at 18:01

1 Answer 1

2

filter does not take multiple arguments. So combine it into one using "and".

var findLat = 3;
var findLng = 4;

var mapSprites = $(xml).find("sprites");
var getSprite = mapSprites.find("sprite").filter(
  function() {
    const node = $(this);
    return Number(node.find('lat').text()) === findLat &&
      Number(node.find('lng').text()) === findLng;
  }
);
Sign up to request clarification or add additional context in comments.

2 Comments

@Taplar Yeah, I noticed that as I added the other code. I removed the unneeded $()
Thank you, fixed! Took me a bit longer because I apparently had some other errors in my code but your answer helped me find those too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.