gpt4 book ai didi

javascript - 将数组对象转换为所需格式的对象数组

转载 作者:行者123 更新时间:2023-12-02 21:40:30 27 4
gpt4 key购买 nike

const getSelectedItemsIds = selectedItemsList => {
let keys = Object.keys(selectedItemsList);
let selectedItems = [];

keys.map(k => {
selectedItemsList[k].map(id => {
if (k.includes("projectIds")) {
return selectedItems.push({ type: "PROJECT", id });
} else if (k.includes("subjectGroupIds")) {
return selectedItems.push({
type: "SUBJECT_GROUP",
id
});
} else if (k.includes("subjectIds")) {
return selectedItems.push({ type: "SUBJECT", id });
}
});
});

return selectedItems;
};

我已经编写了自定义逻辑来获得所需的结果,如果有人可以验证并告诉我是否有更好的方法来做到这一点。我正在添加输入并预期如下:

I/P: 
{
projectIds: [2]
subjectGroupIds: [] // incase multiple subjects are grouped togehter
subjectIds: [4]
}

Expected format:
[{"type":"PROJECT","id":2},{"type":"SUBJECT","id":4}]

提前致谢

最佳答案

    let inputData = { projectIds: [2], subjectGroupIds: [], subjectIds: [4] };
const selectedItems = this.getSelectedItemsIds(inputData);

//Function Definition
getSelectedItemsIds = selectedItemsList => {
let selectedItems = [];
let keys = Object.keys(selectedItemsList)
for ( let k of Object.keys(selectedItemsList)){
keys.forEach(key =>{
if(key === k && selectedItemsList[k].length > 0){
if(key === 'projectIds'){
selectedItems.push({ type: "PROJECT", id: selectedItemsList[k][0]})
}
else if(key === 'subjectGroupIds'){
selectedItems.push({ type: "SUBJECTGROUP", id: selectedItemsList[k][0]})
}
else if(key === 'subjectIds'){
selectedItems.push({ type: "SUBJECT", id: selectedItemsList[k][0]})
}
}
})
}
return selectedItems
}

console.log(selectedItems) //[{type: "PROJECT", id: 2}, {type: "SUBJECT", id: 4}]

关于javascript - 将数组对象转换为所需格式的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60376677/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com