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

How to create from object multiple values array of specified values

I have object:

const data3 = [
  {
    calculatedPropertyDescription: "where evri_courionsignature_gb is Dispatched",
    category: "red",
    tags: [
    { name: 'LandingPage', value: 'true' },
    { name: 'Country', value: 'GB' },
    { name: 'Carrier', value: 'RoyalMail' },
    { name: 'EventCode', value: 'Dispatched' },
    ]
 },
 {
   calculatedPropertyDescription: "where evgnature_gb is Dispatched",
   category: "red",
   tags: [
     { name: 'LandingPage', value: 'true' },
     { name: 'Country', value: 'USA' },
     { name: 'Carrier', value: 'Evri' },
     { name: 'EventCode', value: 'Dispatched' },
   ]
 },
 ]

I need from tags: create array of pairs values.
For exmple from:

{ name: 'LandingPage', value: 'true' },

I need get:

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

[..., 'LandingPage:true', 'Country:GB',...]

Thank you

>Solution :

A simple Array#map() will do:

function mergeKeyValuePairs(tags) {
  return tags.map(({ name, value }) => `${name}:${value}`);
}

Explanation: This means "convert each tag object in a list of tags to a string which is concatenated from the tag’s name, a colon and value". .map() means to do something for every element in a given array.

Try it:

const data3 = [
  {
    calculatedPropertyDescription: "where evri_courionsignature_gb is Dispatched",
    category: "red",
    tags: [
      { name: 'LandingPage', value: 'true' },
      { name: 'Country', value: 'GB' },
      { name: 'Carrier', value: 'RoyalMail' },
      { name: 'EventCode', value: 'Dispatched' },
    ]
 },
 {
   calculatedPropertyDescription: "where evgnature_gb is Dispatched",
   category: "red",
   tags: [
     { name: 'LandingPage', value: 'true' },
     { name: 'Country', value: 'USA' },
     { name: 'Carrier', value: 'Evri' },
     { name: 'EventCode', value: 'Dispatched' },
   ]
 },
];

function mergeKeyValuePairs(tags) {
  return tags.map(({ name, value }) => `${name}:${value}`);
}

console.log(data3);
data3.forEach(
  object => object.tags = mergeKeyValuePairs(object.tags)
);
console.log(data3);
.as-console-wrapper {
  max-height: 100% !important;
}
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