-2

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"}
];
4
  • 1
    "no luck" is not a sufficiently detailed description of what happened when you tried. "gave me errors" is not a sufficiently detailed description of the errors you received. You should copy and paste the exact text of any errors you got into your question, along with the minimum code required to reproduce the issue. Commented Mar 9, 2023 at 14:28
  • 1.) forEach() doesn't natively return anything, so you'd have to explicitly push to your array. 2.) {label: "element", value: "element"}: "element" is a string. You would need {label: element, value: element}. 3.) but no luck isn't specific. What actually happened? An error? An unexpected result? Commented Mar 9, 2023 at 14:28
  • 1
    Does this answer your question? JS : Convert Array of Strings to Array of Objects Commented Mar 9, 2023 at 14:34
  • and Convert array of strings into an array of objects or Convert array of string to array of object using es6 or lodash Commented Mar 9, 2023 at 14:35

1 Answer 1

2

You could take a new array with additional value for mapping.

const
    strings = ["abc", "def", "ghi"],
    result = [...strings, 'Others'].map(value => ({ label: value, value }));

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.