1

I parsed a XML file and retrieved the following JSON-object. The issue is that there are dashes in the json, which causes problems iterating through the object. I can not get rid off them unfortunately.

$(function() {
  let json = JSON.parse('{"app-app":{"$":{},"notneeded":"123","mapped":{"$":{},"match-match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"name":"Foo 3","url":"Bar 3"}]},"Nothing":"123"}}');

  var foo = Object.keys(json['app-app']['mapped']['match-match']).length;
  for (var i = 0; i < foo; i++) {
    console.log(json['app-app']['mapped']['match-match'][i].name);
    console.log(json['app-app']['mapped']['match-match'][i].url);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I would like to iterate through the object and extract every "match" children. Something like this:

return [
            {
                name: 'Foo 1',
                url:  'Bar 1'
            },
            [...]
       ]

Thanks you in advance.

1
  • value.app.mapped.match Commented Mar 27, 2017 at 12:09

2 Answers 2

1

You can simply use Array.prototype.map(), to iterate over your json array and return your custom structure, like this:

$(function() {
  let json = JSON.parse('{"app-app":{"$":{},"notneeded":"123","mapped":{"$":{},"match-match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"name":"Foo 3","url":"Bar 3"}]},"Nothing":"123"}}');


  var result = json['app-app']['mapped']['match-match'].map(function(item) {
    return {
      "name": item.name,
      "url": item.url
    };
  });
  console.dir(result);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

It will give you the expected result.

Sign up to request clarification or add additional context in comments.

Comments

0

let json = JSON.parse('{"app":{"$":{},"notneeded":"123","mapped":{"$":{},"match":[{"$":{},"name":"Foo 1","url":"/Bar 1"},{"$":{},"name":"Foo 2","url":"/Bar 2"},{"$":{},"regex":"Foo 3","configuration":"Bar 3"}]},"Nothing":"123"}}');
console.log(json['app']['mapped']['match']);

1 Comment

@AppRoyale Don't update your question with tries. This will lead to a misunderstanding of the first idea. + Check the array and you will see that the last object has regex and configuration as properties and not name and url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.