Replace certain character and place it to a new value

Viewed 44

I have a problem. I want to replace in my dataList certian values like ., Ü and so on. I also want to add them to a new object value firstname. How could I add the replaced name to firstname? Is this replace a fast way, or is there any better and faster way?


var dataList = [
{ 
    "Name": "Max", 
    "Age": "42",
    "Subname": "Ünger Pes"
},{ 
    "Name": "Bertha", 
    "Age": "53",
    "Subname": "Kl. Fr"
}];

dataList.map(function(item) {
var keyse = Object.keys(item);
for (var i in keyse) {
          item['firstname'[i]] = item[keyse[i]].toLowerCase().replace('.','').replace(' 
          ','').replace('ü','ue');
   }
});

What I got

[
    {
        "Name": "Max",
        "Age": "42",
        "Subname": "Ünger Pes",
        "f": "max",
        "i": "42",
        "r": "uengerpes"
    },
    {
        "Name": "Bertha",
        "Age": "53",
        "Subname": "Kl. Fr",
        "f": "bertha",
        "i": "53",
        "r": "klfr"
    }
]

What I want

[
{ 
    "Name": "Max", 
    "Age": "42",
    "Subname": "Ünger Pes",
    "firstname" : "uengerpes"
},{ 
    "Name": "Bertha", 
    "Age": "53",
    "Subname": "Kl. Fr",
    "firstname" : "klfr"
}]
2 Answers

You can use array#map and for each object introduce a new property firstname derived from Subname.

const data = [{
  "Name": "Max",
  "Age": "42",
  "Subname": "Ünger Pes",
  "f": "max",
  "i": "42",
  "r": "uengerpes"
}, {
  "Name": "Bertha",
  "Age": "53",
  "Subname": "Kl. Fr",
  "f": "bertha",
  "i": "53",
  "r": "klfr"
}];

const result = data.map(({
  Name,
  Age,
  Subname
}) => ({
  Name,
  Age,
  Subname,
  firstname: Subname.toLowerCase()
    .replace(/. /g, '')
    .replace('ü', 'ue')
}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

var dataList = [
{ 
    "Name": "Max", 
    "Age": "42",
    "Subname": "Ünger Pes"
},{ 
    "Name": "Bertha", 
    "Age": "53",
    "Subname": "Kl. Fr"
}];

const result = dataList.map(({Subname, ...rest}) => ({
  ...rest,
  Subname,
  firstname: Subname.replace(/(\.? |\,)/g,'').replace('ü','ue').toLowerCase()
}))

console.log('result = ', result)

Related