Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  52] [ 7]  / answers: 1 / hits: 32769  / 5 Years ago, thu, june 27, 2019, 12:00:00

I have an object like this:



{
responses: {
firstKey: {
items: {
name: test name one
}
},
anotherKey: {
items: {
name: test name two
}
},
oneMoreKey: {
items: {
name: John
}
}
}
}


I need to find all 'name' keys and replace its value only if it starts with 'test name' then return new JSON object:



{
responses: {
firstKey: {
items: {
name: N/A
}
},
anotherKey: {
items: {
name: N/A
}
},
oneMoreKey: {
items: {
name: John
}
}
}
}


The problem is that the keys are not consistent through the objects, i.e. 'firstKey', 'secondKey'... I tried ForEach but it seems to be too cumbersome... So I need either lodash or vanila JavaScript to replace the values.


More From » node.js

 Answers
13

Do something like this. Convert to string replace using regex (add key to regex as well) and then convert back.




var data = {
responses: {
firstKey: {
items: {
name: test name one
}
},
anotherKey: {
items: {
name: test name two
}
},
oneMoreKey: {
items: {
name: John
}
}
}
};

var originalMsg = JSON.stringify(data);
console.log(data)
console.log(originalMsg)
var updatedMsg = originalMsg.replace(/test name [a-z]*/g, N/A);
console.log(updatedMsg)
var newObj = JSON.parse(updatedMsg);
console.log(newObj);


[#51952] Thursday, June 20, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alyssiat

Total Points: 608
Total Questions: 102
Total Answers: 101

Location: Japan
Member since Sat, Jun 6, 2020
4 Years ago
alyssiat questions
;