'Find value in array or object

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



Solution 1:[1]

comment from cmgchess was the solution

const lodash = require("lodash")

lodash.get(object, path)

Solution 2:[2]

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.

Solution 3:[3]

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);

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 NoobDev
Solution 2 Cowgirl
Solution 3
Solution 4 mohamed reda