-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?

2
  • 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. Commented Jan 26, 2019 at 9:12
  • 2
    There is no such thing as a JSON object. Are you asking how to find the index of the {}? Commented Jan 26, 2019 at 9:18

2 Answers 2

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)

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

5 Comments

I think you should return typeof item === 'object' && item !== null instead because if the item in the array is null it will use that as the index
I have added formulaArray && to check if the array is null
Oh, got it, I misunderstood what you meant, thanks
Thank You! but this is not working for number of objects,it is returning only the index for the first object
I have edited the code, now it finds all index and push it to an array
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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.