Home > Mobile >  Solved (Find value in array or object)
Solved (Find value in array or object)

Time:05-16

I want to find a value in a array with a path.

Example:

var object = {
    "value1": [
        "valueinarray": "myvalue"
    ]
}
var array = [
   "value1": {
        "value2": [
             "valueinarray": "myvalue"
        ]
    } 
]

Now I want to get myvalue with a path like value1[0] or [0].value2[0]

I asked a similar question but it dosnt work with array: How do i get the value of an object in a object string

CodePudding user response:

If you are working with JS object as below then it's an incorrect object

var array = [ "value1": { "value2": [ "valueinarray": "myvalue" ] } ]

Object can be refactored as

var array = [ { "value2": [ {"valueinarray": "myvalue"} ] } ]

And values can be fetched as below

array[0].value2[0]

Not sure if thats your question.

CodePudding user response:

Your syntax of assigning value to the array is wrong. You need to use curly bracket { } for putting key value pair in an array. For example : value2: [ { "valueinarray": "myvalue"} ].

var object = {
              "value1": [
                {
                  "valueinarray": "myvalue"
                }
              ]
            }

console.log(object.value1[0].valueinarray);

var array = [
              {
                "value1": {
                  "value2": [
                    {
                      "valueinarray": "myvalue"
                    }
                  ]
                }
              }
            ]
            
console.log(array[0].value1.value2[0].valueinarray);

CodePudding user response:

console.log(object.value1[0].valueinarray);
var array = [{"value2": ["myvalue"]}];
console.log(array[0]['value2'][0]);
  • Related