Search code examples
javascriptnode.jsnodes

getting nested value by using node js / javascript


let data =
 [
    {
        "testingNewValue": {
            "en-US": "hello"
        }
    },
    {
        "testingNewValue": {
            "hi-IN": "hello "
        }
    },
    {
        "testingNewValue": {
            "us": "dummy"
        }
    },
    {
        "testingNewValue": {
            "xp-op-as": "value for testing"
        },
        "locationField": {
            "en-US": {
                "lat": 19.28563,
                "lon": 72.8691
            }
        }
    }
]

const value = Object.fromEntries(Object.entries(data).map(el=>(el[1]=Object.values(el[1])[0], el)))
    console.log(value);

I am trying to get value from the data json by using the object.fromEntries n object.entries but its not working as my expectation as I am expecting the value as

Expectation

{
  {
    testingNewValue:"hello"
  },
  {
    testingNewValue:"hello"
  },
  {
    testingNewValue:"dummy"
  },
  {
    testingNewValue:"value for testing",
    locationField:{
      lat: 19.28563,
      lon: 72.8691
    }
  }
}

but I am getting "0","1","2" as you can see in code snippet as I want to remove all "en-US","hi-In" n all from data

How can I get my expectation


Solution

  • Provided that you're actually after an array (as your current expected result isn't a valid structure), you should be taking the entires of each inner objects and then taking building your new object with fromEntries() after mapping each entry, rather then taking the entires of your entire data array which is causing the indexes to appear in your current result. The below code assumes you have one value within each inner object, and that each value is an object:

    const data = [ { "testingNewValue": { "en-US": "hello" } }, { "testingNewValue": { "hi-IN": "hello " } }, { "testingNewValue": { "us": "dummy" } }, { "testingNewValue": { "xp-op-as": "value for testing" }, "locationField": { "en-US": { "lat": 19.28563, "lon": 72.8691 } } } ];
    
    const value = data.map(el=>
      Object.fromEntries(Object.entries(el).map(([k, v]) => [k, Object.values(v)[0]]))
    );
    console.log(value);