0

I have JSON collection object like this

"Sections":[
    {"SectionName":"Dallas", ...}, 
    {"SectionName":"Austin", ...}, 
    {"SectionName":"Housto", ...}
]

If I want search for string "Austin" - how can I search directly without looping?

I am doing this but it is not straight.

 if (sections.length > 0) {
               $.each(sections, function(myObject) {
                   var sectionObject = sections[myObject];

                   if (Object.keys(sectionObject).length > 0 && sectionObject["SectionName"] != undefined) {
                    ...
                   }
               });
4
  • You will have loop through your array once. There is no other way here. Obviously, not considering an option to implement one of the search algorithms. But I think, that's not what you meant? Commented May 4, 2016 at 20:09
  • 4
    What's wrong with looping? Commented May 4, 2016 at 20:09
  • @Uzbekjon not true! You can do it manually, and then die internally when you're asked to change things. Commented May 4, 2016 at 20:09
  • @SterlingArcher can't disagree! The truth is yours :) Commented May 4, 2016 at 20:11

1 Answer 1

2

You can use Filter and return only objects which contains "SectionName": "Austin"

var data = {
  "Sections": [{
    "SectionName": "Dallas",
  }, {
    "SectionName": "Austin",
  }, {
    "SectionName": "Housto",
  }]
}

data = data['Sections'].filter(el => el['SectionName'] == 'Austin');
console.log(data)

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

1 Comment

Mandatory lambda syntax because: data = data['Sections'].filter(el => el['SectionName'] = 'Austin');

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.