Returning a array of objects by reducing and array

30
November 24, 2021, at 01:30 AM

I'm trying to return an array of objects from an array. So for example. I have an array of strings:

const strArr = ["Some", "Thing"];

And I need to return an Array with 2 objects for each position from the strArr, for example:

result:
[{first_key: "Some"}, {second_key: "Some"}, {first_key: "Thing"}, {second_key: "Thing"}]

I have done this, which works, but I rather work without let:

const numeros = ["some", 'thing']
let arr = [];
numeros.map(valor => {
    const titleContains = {
      title_contains: valor,
    }
    const bodyContains = {
      body_contains: valor,
    }
    
    arr.push(titleContains);
    arr.push(bodyContains);
});
console.log(arr)

This code gives me the right result, althought map is being used wrong and I'm have to use a let which I don't want to.

Answer 1

You could take Array#flatMap and return two objects for each value.

const
    data = ["Some", "Thing"],
    result = data.flatMap(valor => [{ first_key: valor }, { second_key: valor }]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer 2

Here's a version with a reduce, you can read more about it here :)

const numeros = ["some", 'thing']
const arr = numeros.reduce((acc, valor) => {
    const titleContains = {
      title_contains: valor,
    }
    const bodyContains = {
      body_contains: valor,
    }
    
    acc.push(titleContains);
    acc.push(bodyContains);
    return acc;
}, []); // <==== note an empty array here.
console.log(arr)

READ ALSO
Android java foreground service

Android java foreground service

foreground service keeps particular activity in background or whole app , Like am making an app which gets values from sensorand fetch location

32
Linker Errors When Attempting to Run Example Program for MySQL Connector/C++ 8.0.27 (Windows)

Linker Errors When Attempting to Run Example Program for MySQL Connector/C++ 8.0.27 (Windows)

I have been trying to successfully build and run a test of the MySQL Connector/C++ 80

55
How to properly select document via populate from another document with mongoose?

How to properly select document via populate from another document with mongoose?

I did a select with populate and it works, but feel like there is a better way

41
How to add only one click event on a label?

How to add only one click event on a label?

Hello i'm trying to add an event of click on a button when the user click a label, its working fine but the user have to click on the label twice i need to make it work from the first click this is my function :

35