How to catch a json object with match

Asked

Viewed 58 times

2

Good morning, I have a json with the following format:

{
  "code_name_1001": "Antônio",
  "code_name_1002": "Luis",
  "code_name_1003": "Alice",
  "code_name_1004": "Julia"
}

my doubt is on how I can get each code and the name associated with the code, for example //output 1001: Antônio 1002: Luis

in my view I will have to use match and replace to catch both, but I do not know how to perform

1 answer

2


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

    +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 ;).

  • 1

    Thanks for the suggestion, I edited the reply adding an explanation to regex and inserting some links references.

  • 1

    Wow, that was definitely a great explanation, thank you very much!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.