映射ES6中的嵌套数组



这里有一个嵌套数组。内部数组只有一个数据。有什么方法可以改进吗?喜欢使用[0]最小化吗?使用现代JS。

注意:我将状态重命名为myStatus

let response = [
{
"data": [
{
"name": "Hello",
"status": "There"
}
],

},
{
"data": [
{
"name": "Hello",
"status": "There"
}
],

}
];

const finalDatas = response?.map((value) => {
return {
name: value?.data?.[0]?.name,
myStatus: value?.data?.[0]?.status
};
});

console.log(finalDatas)

你可以试试这个:

const response = [
{
"data": [
{
"name": "Hello",
"status": "There"
}
],

},
{
"data": [
{
"name": "Hello",
"status": "There"
}
],

},
{
"data": [ // name: undefined, status: null
{
"status": null
}
],

},
{
"data": [ // data array with empty object
{}
],
},
{
"data": [], //empty array - this doesn't end up in the result list
},
];
const res = response.flatMap(({data}) => [...data].map(item => {
return {
name: item.name,
myStatus: item.status,
};
}));
console.log(res);

编辑:我在这个片段中添加了更多的案例。正如您所看到的,只要数据列表中有对象,此代码就会在结果列表中生成一个条目。

尝试使用以下代码片段。这可能会有所帮助。

let response = [
{
"data": [
{
"name": "Hello",
"status": "There"
}
],

},
{
"data": [
{
"name": "Hello",
"status": "There"
}
],

}
];
let renameKey = ( obj, oldKey, newKey ) => {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
return obj
}
let output = response.map(data => renameKey(data.data[0], "status", "myStatus"));
console.log(output);

您可以使用flatMap和排列

不重命名

const finalDatas = response.flatMap(({data}) => [...data]);

评论后更新:代码需要在的某个位置

const ren = (obj, oldKey, newKey) => {
obj = obj.pop();
return delete Object.assign(obj, {[newKey]: obj[oldKey]})[oldKey], obj;
}
const finalDatas = response.map(({data}) => ren(data, "status", "myStatus"));
console.log(finalDatas);
<script>
let response = [{
"data": [{
"name": "Hello",
"status": "There"
}],
},
{
"data": [{
"name": "Hello",
"status": "There"
}],
}
];
</script>

最新更新