如何将数组元素放入对象值?

huangapple go评论122阅读模式
英文:

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 = [&quot;abc&quot;, &quot;def&quot;, &quot;ghi&quot;],
    result = [...strings, &#39;Others&#39;].map(value =&gt; ({ label: value, value }));

console.log(result);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年3月9日 22:18:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685836.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定