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

One liner javascript function to edit value of specific property from array of objects

Say, I have array of objects:

arr = [
    {path: 'mexico', name: 'mexico'},
    {path: 'brazil', name: 'brazil'},
    {path: 'netherlands', name: 'netherlands'}
];

What I want to achieve:

prefix = 'country/'
arr = [
    {path: 'country/mexico', name: 'mexico'},
    {path: 'country/brazil', name: 'brazil'},
    {path: 'country/netherlands', name: 'netherlands'}
];

Is there a one liner javascript function that append the prefix country/ into the path property of all objects in the array?

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

perhaps, something like this: arr.append(prefix, arr, 'path');

>Solution :

You could use a forEach and a concat:

arr = [
    {path: 'mexico', name: 'mexico'},
    {path: 'brazil', name: 'brazil'},
    {path: 'netherlands', name: 'netherlands'}
];
prefix = 'country/';
arr.forEach(x => x.path = prefix.concat(x.path));
console.log(arr);
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