-2

I am having a simple sample code as follows:

var sampleObj = [{prop1 : ""}, {prop2 : ""}, {propArr : [{key : "", value : ""}, {key : "", value : ""}]}];

This is a JSON Object that has some properties including a property that contains an array.

My Question

I need to use the JS method indexOf() to get the index of [propArr] using the key not the value.

for example I need a way to implement this:

var index = sampleObj.indexOf(propArr);
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 1
    *"This is a JSON Object"* JSON is a *textual notation* for data exchange. [(More here.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. – T.J. Crowder Nov 10 '21 at 18:32
  • 5
    Why do you *need* to use `indexOf`? What makes this restriction necessary? – VLAZ Nov 10 '21 at 18:32
  • Also, instead of an array of objects (which you confusingly call `sampleObj`), why not have an actual object with properties, and then they would be simple to access: `const obj = { prop1: 1, ... };` and then `console.log(obj.prop1)`. Then you don't need the index. – Andy Nov 10 '21 at 18:36

1 Answers1

2

Use findIndex:

var sampleObj=[{prop1:""},{prop2:""},{propArr:[{key:"",value:""},{key:"",value:""}]}];

const prop = "propArr"

const res = sampleObj.findIndex(e => Object.keys(e)[0] == prop)
console.log(res)

If you strictly need to use indexOf, you can map through the array to extract the first property of each object, then use indexOf:

var sampleObj=[{prop1:""},{prop2:""},{propArr:[{key:"",value:""},{key:"",value:""}]}];

const prop = "propArr"

const res = sampleObj.map(e => Object.keys(e)[0]).indexOf(prop)
console.log(res)
Spectric
  • 30,714
  • 6
  • 20
  • 43