使用nodejs/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);

我试图通过使用object.fromEntries n object.entries从数据json中获取值,但它并没有像我预期的那样工作,因为我预期的值是

期望

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

但我得到了";0"1〃"2〃;正如你在代码片段中看到的,因为我想删除所有";en-US"hi In";n全部来自数据

如何获得我的期望

假设您实际上在寻找一个数组(因为您当前的预期结果不是一个有效的结构(,您应该获取每个内部对象的整数,然后在映射每个条目后使用fromEntries()构建新对象,而不是获取导致索引出现在当前结果中的整个data数组的整数。下面的代码假设每个内部对象中都有一个值,并且每个值都是一个对象:

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

最新更新