-2

I have an array like below

let formulaArray = ["(", "(", "(", "2", "+", "3", ")", "*", "3", ")", "+", "(", "12", "/",{}]
 }

json object in an array can be at any index.Now,I want to find the index of json object ,how can i do that?

valli
  • 103
  • 2
  • 11
  • please change the data structure to a valid one. objects does not contain items without any key and arrays does not have keys in literal notation. – Nina Scholz Jan 26 '19 at 09:12
  • 2
    There is no such thing as a JSON object. Are you asking how to find the index of the `{}`? –  Jan 26 '19 at 09:18

2 Answers2

2

Use .forEach() and then check the object with typeof operator, if true, then push it to an array

var formulaArray = ["(",{}, "(", "(", "2", "+", "3", ")", "*", "3", ")", "+", "(", "12", "/",null,{}]
var objectIndex = [];
formulaArray && formulaArray.forEach(function(item, index){
    typeof item==='object' && item!==null && 
objectIndex.push(index);
})
console.log(objectIndex)
Alvin Theodora
  • 936
  • 1
  • 11
  • 18
0

Please check out this SO answer https://stackoverflow.com/a/36419269/3902739

It defines the correct structure of an array of Json objects and uses JavaScript functions such as Array.find or Array.forEach or Array.filter as clearly explained in the example provided.

Hope this helps!

AllJs
  • 1,760
  • 4
  • 27
  • 48