0

Is there any efficient way to construct an object from an array of string in LWC?

const layerArr = ['Comp Type', 'Region', 'Industry'];

OUTPUT

const targetObj = [
    {
        "name": "Comp Type",
        "options": "comptypeOptions",
        "taxLabel": "comptypeLabel"
    },
    {
        "name": "Region",
        "options": "regionOptions",
        "taxLabel": "regionLabel"
    },
    {
        "name": "Industry",
        "options": "industryOptions",
        "taxLabel": "industryLabel"
    }
]

I am using reduce function but it's not woking here and also I want to use toLowerCase() on the fly while assigning the key too.

layerObject = this.layerOptions.reduce(function (result, item, index) {
    result['name'] = item;
    result['options'] = item.replace(' ', '').toLowerCase() + 'Options';
    result['taxLabel'] = item.replace(' ', '').toLowerCase() + 'Label';
    return result
}, {})

2 Answers 2

2

Your transformation can be accomplished with Array.prototype.map:

let x; // Used inside callback
this.layerObject = 
  this.layerOptions.map(v => (x = v.replace(' ','').toLowerCase(), { 
    name: v, 
    options: `${x}Options`, 
    taxLabel: `${x}Label`
  }));

Some notes:

The arrow function uses x => y as a notation for parameter x fed into the next expression, and y is returned as the result. However, if we want multiple lines of execution, we write x => { y }. To get an object literal, we need to wrap that in parentheses, resulting in x => ({ y }), which is why it's written this way in the example.

The Array.prototype.map function iterates over every item in an array, and transforms it per the callback function. We use this feature to map the string into the three-property object that you're trying to achieve.

The string in backticks (\) is a Template Literal, which we use to substitute expressions in without extra string concatenation. The ${...} syntax is evaluated as a normal expression, which is how we transform the latter two properties as you desire.

The original map isn't modified when using Array.prototype.map; a new Array is returned instead.

The comma operator performs the operation on the left, then the right, and returns the value on the right.

By the way, Array.prototype.reduce is used to convert an array into a single object or result, such as [1,3,5].reduce((a,b) => (a + b), 0) to output 8 (1 + 3 + 5). It's useful in a lot of cases, but not here.

0

You almost had it:

layerObject = this.layerOptions.reduce(function (result, item) {
    let lcItem = item.replace(' ', '').toLowerCase();
    result.append({
        name: item,
        options: `${lcItem}Options`,
        taxLabel: `${lcItem}Label`
    });
    return result;
}, []);

As per your requirements you want to reduce to an Array ([]) and not an object ({}), that's the main thing.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .