0
    const data = [
   {0: {id: "1",cat:{string:[{color:"yellow",weight:"10"},{color:"orange",Weight:"10"}]}},
   {1: {id: "1",cat:{string:[{color:"blue",weight:"10"},{color:"orange",Weight:"10"}]}},
   {2: {id: "1",cat:{string:[{color:"white",weight:"10"},{color:"orange",Weight:"10"}]}},
   {3: {id: "1",cat:{string:[{color:"blue",weight:"10"},{color:"orange",Weight:"10"}]}},
]

Filter by Color: "Yellow"

Desired Output: [{0: {id: 1, country: "SA", address: "IOXX",cat:[{color: "yellow",weight: "10"}]}}]

3
  • 1
    Does this answer your question? Filtering nested JSON javascript Commented Nov 9, 2021 at 5:34
  • Is it possible that cat Array has multiple objects? If yes, what would you expect? Should all of the objects have the color of Yellow to return that record? Or if just one of them pass the condition you'll accept that? Commented Nov 9, 2021 at 5:35
  • I updated the exact structure in question Commented Nov 9, 2021 at 6:40

2 Answers 2

0

You can use filter() method

const data = [
    { 0: { id: "1", cat: { string: [{ color: "yellow", weight: "10" }, { color: "orange", Weight: "10" }] } } },
    { 1: { id: "1", cat: { string: [{ color: "blue", weight: "10" }, { color: "orange", Weight: "10" }] } } },
    { 2: { id: "1", cat: { string: [{ color: "white", weight: "10" }, { color: "orange", Weight: "10" }] } } },
    { 3: { id: "1", cat: { string: [{ color: "blue", weight: "10" }, { color: "orange", Weight: "10" }] } } }
];

var res = data.filter((el, i) => data[i][i]['cat']['string'][0]['color'] === 'yellow');

console.log(res);

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

2 Comments

Updated actual structure its has one additional layer of complexity.
@Powershell-Guy, I made update of my post
0

You can map over your data array and check if each object passes your conditions or not.

const data = [
 {0: {id: 1, country: "SA", address: "IOXX",cat:[{color: "yellow",weight: "10"}]}},
 {1: {id:2, country: "SAP", name: "N", address: "IOP",cat:[{color: "blue",weight: "10"}]}},
 {2: {id:3, country: "S", name: "NO", address: "I",cat:[{color: "blue",weight: "10"}]}},
 {3: {id:4, country: "SXX", name: "NOI", address: "INDIA",cat:[{color: "blue",weight: "12"}]}},
]

const filterByColor = function (color) {
  const filteredCats = []
  data.forEach((item, index) => {
    const hasCorrectColor = item[index].cat.every((cat) => cat.color === color)
    if (hasCorrectColor) {
       filteredCats.push(item)
    }
      
  })
  return filteredCats
}

filterByColor('yellow')

1 Comment

updated to actual structure its got one more layer .

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.