0

I have the following payload (small sample) being returned from an api as an Object.

{
"0hmITkwFMbB2BDIUFlFm": {
    "price": 89,
    "categories": ["wireless", "broadband"],
    "companyname": "T-Mobile",
    "symbol": "TMUS"
},
"8g570i57at8yTjoZtSuk": {
    "companyname": "Microsoft",
    "symbol": "MSFT",
    "price": 181.25,
    "categories": ["technology", "software"]
},
"OMc8V4AVH5q5z0Sis8vp": {
    "companyname": "Amazon",
    "symbol": "AMZN",
    "price": 2419.49,
    "categories": ["E-commerce", "consumer products"]
},

I want to be able to return each object that includes a given value in the categories array. For example, returning all object that includes "technology" in the categories array.

How can I do this in javascript?

0

3 Answers 3

1
const obj = {
"0hmITkwFMbB2BDIUFlFm": {
    "price": 89,
    "categories": ["wireless", "broadband"],
    "companyname": "T-Mobile",
    "symbol": "TMUS"
},
"8g570i57at8yTjoZtSuk": {
    "companyname": "Microsoft",
    "symbol": "MSFT",
    "price": 181.25,
    "categories": ["technology", "software"]
},
"OMc8V4AVH5q5z0Sis8vp": {
    "companyname": "Amazon",
    "symbol": "AMZN",
    "price": 2419.49,
    "categories": ["E-commerce", "consumer products"]
}
}

const filteredObjects = Object.keys(obj).reduce((acc, rec) => {
  if (obj[rec].categories.includes('technology'))
    return [...acc, obj[rec]]
  return acc;
}, [])

console.log(JSON.stringify(filteredObjects))

following code allows you to get filtered array of objects, that satisfy your given condition.

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

Comments

0

Try is

let filteredObjects = [];
Object.keys(sampleObjects).map((key) =>{
   if (sampleObjects.indexOf('technology') != -1) {
      filteredObjects.push(sampleObjects[key];
   }
});

Comments

0
let response = {
  "0hmITkwFMbB2BDIUFlFm": {
    "price": 89,
    "categories": ["wireless", "broadband"],
    "companyname": "T-Mobile",
    "symbol": "TMUS"
  },
  "8g570i57at8yTjoZtSuk": {
    "companyname": "Microsoft",
    "symbol": "MSFT",
    "price": 181.25,
    "categories": ["technology", "software"]
  },
  "OMc8V4AVH5q5z0Sis8vp": {
    "companyname": "Amazon",
    "symbol": "AMZN",
    "price": 2419.49,
    "categories": ["E-commerce", "consumer products"]
  }
}

let newObject = {}

for (const property in response) {
  if (response[property].categories.indexOf("technology") > -1) {
    newObject[property] = response[property];
  }
}

console.log(newObject)

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.