2

I have following object in JS:

[
  {
    "financial_year":1,
    "mainline_revenue":18743.0,
    "regional_revenue":2914.0,
    "other_revenue":3198.0,
    "non_operating_items":-1983.0
  },
  {
    "financial_year":2,
    "mainline_revenue":20218.0,
    "regional_revenue":3131.0,
    "other_revenue":3394.0,
    "non_operating_items":-3233.0
  },
  {
    "financial_year":3,
    "mainline_revenue":30802.0,
    "regional_revenue":6322.0,
    "other_revenue":5526.0,
    "non_operating_items":-1367.0
  }
]

financial_year is the unique identifier which I want to use to filter data. How can I filter data where for example financial_year is 2 and put the other values in an array?

4
  • 2
    google: MDN array methods. You need filter. Commented Aug 18, 2017 at 15:44
  • 4
    Possible duplicate of How to filter an object with its values in ES6 Commented Aug 18, 2017 at 15:45
  • have you tried anything? Commented Aug 18, 2017 at 15:45
  • This is an array of objects. Not a dictionary. Commented Dec 29, 2021 at 18:31

1 Answer 1

8

You can use the filter method on arrays. filter takes a callback which returns true or false (more accurately, a truthy or falsey value). If it returns true, that object is included in the resulting array.

let input = [
  {
    "financial_year":1,
    "mainline_revenue":18743.0,
    "regional_revenue":2914.0,
    "other_revenue":3198.0,
    "non_operating_items":-1983.0
  },
  {
    "financial_year":2,
    "mainline_revenue":20218.0,
    "regional_revenue":3131.0,
    "other_revenue":3394.0,
    "non_operating_items":-3233.0
  },
  {
    "financial_year":3,
    "mainline_revenue":30802.0,
    "regional_revenue":6322.0,
    "other_revenue":5526.0,
    "non_operating_items":-1367.0
  }
];
let output = input.filter((obj) => obj.financial_year !== 2);
console.log(JSON.stringify(output, null, 2));

Or rewritten with ES5:

var input = [
  {
    "financial_year":1,
    "mainline_revenue":18743.0,
    "regional_revenue":2914.0,
    "other_revenue":3198.0,
    "non_operating_items":-1983.0
  },
  {
    "financial_year":2,
    "mainline_revenue":20218.0,
    "regional_revenue":3131.0,
    "other_revenue":3394.0,
    "non_operating_items":-3233.0
  },
  {
    "financial_year":3,
    "mainline_revenue":30802.0,
    "regional_revenue":6322.0,
    "other_revenue":5526.0,
    "non_operating_items":-1367.0
  }
];
var output = input.filter(function(obj) {
  return obj.financial_year !== 2;
});
console.log(JSON.stringify(output, null, 2));

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

Comments

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.