英文:
How to put array elements into object values?
问题
const stringsArray=["abc", "def", "ghi"];
const stringsObjects=[
{ label: "abc", value: "abc"},
{ label: "def", value: "def"},
{ label: "ghi", value: "ghi"},
{ label: "Others", value: "Others"}
];
const obj2 = stringsArray.map(element => ({label: element, value: element}));
const selectOptions = stringsArray.map(keyword => ({value: keyword, label: keyword})).concat([{value: "Others", label: "Others"}]);
英文:
I have an array of several strings like:
const stringsArray=["abc", "def", "ghi"];
I want to convert it into objects like:
const stringsObjects=[
{ label: "abc", value: "abc"},
{ label: "def", value: "def"},
{ label: "ghi", value: "ghi"},
{ label: "Others", value: "Others"}
];
I need to add one more object to the last with values as "others" as above.
I tried using map and forEach methods but no luck. Can anyone guide me here using javascript here?
I tried using map and forEach methods but no luck.
const obj2= array1.forEach(element => {label: "element", value: "element"});
const selectOptions = industryKeywords.map(keyword => {return({
value: keyword,
label: keyword
},
{
value: "Others",
label: "Others"
}
)})
Both these ways gave me errors.
I expect the below result:
const stringsObjects=[
{ label: "abc", value: "abc"},
{ label: "def", value: "def"},
{ label: "ghi", value: "ghi"},
{ label: "Others", value: "Others"}
];
答案1
得分: 2
你可以使用包含额外值的新数组进行映射。
const
strings = ["abc", "def", "ghi"],
result = [...strings, 'Others'].map(value => ({ label: value, value }));
console.log(result);
英文:
You could take a new array with additional value for mapping.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const
strings = ["abc", "def", "ghi"],
result = [...strings, 'Others'].map(value => ({ label: value, value }));
console.log(result);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论