Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returning a array of objects by reducing and array

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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; }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading