You can create a new object with the key being the code and the value being the name, for this you can use a for in
to traverse the keys of your object in this way:
const obj = {
"code_name_1001": "Antônio",
"code_name_1002": "Luis",
"code_name_1003": "Alice",
"code_name_1004": "Julia"
}
let newObj = {}
for(o in obj) {
const key = o.match(/\d*$/)[0]
newObj[key] = obj[o]
}
When doing the match, I step a regex to get only the numbers:
\d
: Set equivalent [0-9]
, this way you can get the digits present in string
.
*
: Zero quantifier or more occurrences, with it it is possible to capture the occurrences of the set \d
.
$
: It means the end of the text or a line, so we can capture only the numbers that are at the end (in your case all the numbers after the last occurrence of the character _
).
Thus newObj
will have that format: { 1001: "Antônio", 1002: "Luis", 1003: "Alice", 1004: "Julia" }
, now just take the values, for example:
Object.keys(newObj).forEach(key => console.log(`${key}: ${newObj[key]}`))
In that case I’m using the Object.keys
to take the object keys and turn it into an array, the output would be like this: [ "1001", "1002", "1003", "1004" ]
, after that I make a forEach
to scroll through the generated array and output to the console.
const obj = {
"code_name_1001": "Antônio",
"code_name_1002": "Luis",
"code_name_1003": "Alice",
"code_name_1004": "Julia"
}
let newObj = {}
for(o in obj) {
const key = o.match(/\d*$/)[0]
newObj[key] = obj[o]
}
Object.keys(newObj).forEach(key => console.log(`${key}: ${newObj[key]}`))
References:
Regex: A practical guide to regular expressions
for...in
+1 Very good, but for the explanation to be better, I think it would be good to explain this Regex to be clearer for the AP ;).
– Cmte Cardeal
Thanks for the suggestion, I edited the reply adding an explanation to regex and inserting some links references.
– Gabriel José de Oliveira
Wow, that was definitely a great explanation, thank you very much!!
– AndreLps