Home > OS >  Want to merge two line with same keys but different values in javascript
Want to merge two line with same keys but different values in javascript

Time:07-25

I have a javascript string array of tokens to be processed by nodejs to change the output. Need to merge the values of the same string prefix.

What I have:

[
"$button-primary-font-color-default: ('light':#000);",
"$button-primary-font-color-default: ('dark':#fff);"
]

What I want:

["$button-primary-font-color-default: ('light':#000, 'dark':#fff);"]

I have tried array.filter with no success. I´m not so good with regular expressions.

Thank you for any help with this.

CodePudding user response:

First, I create an object to group each key with array of it's values, for example.

{
   "$button-primary-font-color-default:": ["'light':#000", "'dark':#fff"]
}

Then I maped the object to be as string format.

const data = [
"$button-primary-font-color-default: ('light':#000);",
"$button-primary-font-color-default: ('dark':#fff);"
]


const obj = data.reduce((acc, i) => {
  const key = i.match(/\$.*?:/)
  const [_, value] = i.match(/\(('\w ':#[0-9a-f]{3})\);/i)
  if (acc[key]) {
    acc[key] = [...acc[key], value]  
  } else {
    acc[key] = [value]
  }
  return acc
}, {})


const result = Object.entries(obj).map(([key, value]) => {
  return `${key} (${value.join(', ')})`
})

console.log(result)

CodePudding user response:

Grouping by property name using reduce method. Then flatenning the solution into the required format. This is similar to other answers, only a little more generic with the properties.

var input = [
  "$button-primary-font-color-default: ('light':#000);",
  "$button-primary-font-color-default: ('dark':#fff);",
  "$button-secondary-font-color-default: ('secondary':red);"
];


var step1 = input.reduce(function(agg, line) {
  var prop = line.slice(0, line.indexOf(':')).trim();
  var value = line.slice(line.indexOf(':')   1, line.indexOf(';')).trim().slice(1, -1);
  agg[prop] = agg[prop] || []
  agg[prop].push(value)
  return agg;
}, {})


var result = Object.entries(step1).map(function([prop,value]) {
  return prop   " "   "("   value.join(", ")   ")";
});

console.log(result)

  • Related