将列表转换为具有新属性名称的另一个新列表
Posted
技术标签:
【中文标题】将列表转换为具有新属性名称的另一个新列表【英文标题】:covert list into another new list with new property name 【发布时间】:2021-10-11 01:41:46 【问题描述】:我有一个列表看起来像所有设置。我想将该列表转换为新列表。由于我是新手,所以我没有太多想法,我尝试按照以下方式进行操作,但新列表中的第一项始终为空。
const [mySetting, setMySet] = useState([]);
useEffect(() =>
const allSettings = [
name: "Setting1", value: true, label: 1 ,
name: "Setting2", value: true, label: 2 ,
name: "Setting3", value: true, label: 3 ,
name: "Setting4", value: false, label: 4 ,
name: "Setting5", value: true, label: 5 ,
name: "Setting6", value: true, label: 6 ,
name: "Setting7", value: true, label: 7
];
const settings = [];
const allSettingsMap = allSettings.reduce((resMap, current) =>
settings.push(resMap);
return
...resMap,
SettingID: current.label,
Name: current.name,
value: current.value
;
, );
setMySet(settings);
, []);
//我想要这样的新列表:
const newSettings = [
name: "Setting1", value: true, SettingID: 1 ,
name: "Setting2", value: true, SettingID: 2 ,
name: "Setting3", value: true, SettingID: 3 ,
name: "Setting4", value: false, SettingID: 4 ,
name: "Setting5", value: true, SettingID: 5 ,
name: "Setting6", value: true, SettingID: 6 ,
name: "Setting7", value: true, SettingID: 7
];
【问题讨论】:
【参考方案1】:您可以使用array#map
重命名对象中的键并保持其他键不变。对于每个对象,您可以选择 label
并将其重命名为 SettingID
并保持其他键值相同。
const allSettings = [ name: "Setting1", value: true, label: 1 , name: "Setting2", value: true, label: 2 , name: "Setting3", value: true, label: 3 , name: "Setting4", value: false, label: 4 , name: "Setting5", value: true, label: 5 , name: "Setting6", value: true, label: 6 , name: "Setting7", value: true, label: 7 ],
result = allSettings.map((label, ...other) => (...other, SettingID: label));
console.log(result);
.as-console-wrapper max-height: 100% !important; top: 0;
【讨论】:
【参考方案2】:用这个 map 方法替换你的 allSettings.reduce 方法
const settings = [];
allSettings.map((setting) =>
const item = ...setting ;
const tempValue = item?.label;
// delete item label
delete item["label"];
item["SettingID"] = tempValue;
settings.push(item);
);
【讨论】:
【参考方案3】:您可以通过数组上的映射轻松做到这一点
const allSettings = [
name: "Setting1", value: true, label: 1 ,
name: "Setting2", value: true, label: 2 ,
name: "Setting3", value: true, label: 3 ,
name: "Setting4", value: false, label: 4 ,
name: "Setting5", value: true, label: 5 ,
name: "Setting6", value: true, label: 6 ,
name: "Setting7", value: true, label: 7
];
const newAllSettings = allSettings.map(item =>
return
name: item.name,
value: item.value,
SettingID:item.label
;
);
console.log(newAllSettings)
【讨论】:
以上是关于将列表转换为具有新属性名称的另一个新列表的主要内容,如果未能解决你的问题,请参考以下文章
Drools将一个对象的列表转换为drools中的另一个对象的列表