JavaScript recursive replace in Object - javascript

Folks, I have the following JSON object, in which I would like to recursively find every occurrence of foo with bar.
Also the [Object] can potentially contain foo which would also need to be replaced.
{ _id: 530797d8952e10129f97fde3,
Product: 'something',
Realm: [ 'something', 'something','foo' ],
Service: 'Node',
Owners: [ 'foo', 'something' ],
Project: 'something',
URLs:
[ { 'foo': [Object] },
{ 'foo': [Object] },
{ 'foo': [Object] } ] }
How would i loop through this? I've tried with but failed:
var cleanObject = {}
for (key in dirtyObject) {
key = key.replace('foo', 'bar');
cleanObject[key] = dirtyObject[key];
}

Tip: That's not a "JSON object". There is no such thing as a "JSON object". "JSON" is a string, representing an object. What you have there is an object literal.
However, JSON can help. Consider trying:
var cleanObject = JSON.parse(JSON.stringify(dirtyObject).replace(/foo/g,'bar'));

Related

Javascript Mapping Array of Objects within an Array

I know there have been some similar questions before but I'm really stuck on trying to map the below array of information (I've tried to implement several example). I have an Array with two information fields and a third field that contains Arrays of objects. I want to extract the name of each of the objects into the original name so that my output looks like the below:
Desired Output:
[gameId, gameName, gameGenresArray]
Below is a sample of what the data looks like:
Data = [ 270722, 'The Wild at Heart', [ [Object], [Object], [Object] ] ],
[ 558984, 'Knockout City', [ [Object] ] ],
[ 558982, 'Miitopia', [ [Object], [Object] ] ],
[ 45775, 'Biomutant', [ [Object], [Object] ] ]
The [Object] has a property called gameGenre that I want to store in the original array as an array instead of as an Array of Objects.
My most recent attempt was:
var result = data.map(({ id, name, [{gameGenres}] }) => ([id, name, gameGenres]))
I appreciate any help anyone can add!
Thanks!!
I think this is what you want:
const Data = [
[
270722,
'The Wild at Heart', [{
name: 'action'
}, {
name: 'horror'
}, {
name: 'adventure'
}],
],
[558984, 'Knockout City', [{
name: 'action'
}]],
[558982, 'Miitopia', [{
name: 'action'
}, {
name: 'rpg'
}]],
[45775, 'Biomutant', [{
name: 'casual'
}, {
name: 'platform'
}]],
];
const result = Data.map(item => {
return {
gameId: item[0],
gameName: item[1],
gameGenresArray: item[2].map(genre => genre.name),
};
});
console.log(result);
You need to map each object and then - when you have an array in an object - map within the map. Easiest to save them in variables:
let gameid, gamename, gamegenre;
Data.map((game) => {gameid=game.id;
gamename=game.name;
game.map((genre) => gamegenre+=genre)})
let result = [gameid, gamename, gamegenre]
Probably needs to be modified, but I don't know how you objects looks.

coverting the string to json object

I tried to display my data in json format. Firstly i tried JSON.stringify
then it shows in string format so, then again I tried JSON.parse where I get like array of object finally I tried keeping [0] to the parse object it throws 'undefined'...
can you please tell me where I am doing wrong..
I provide the output of the following console.log..
try{
var timekeep = await Orders.findAndCountAll(
{
where : {
cid : orders_info.cid,
},
order: [
['id', 'DESC']
],
limit: 1,
}
);
console.log("RESULT => ", timekeep);
var datjsn = JSON.stringify(timekeep);
var jsonsr = JSON.parse(datjsn);
var data23 = jsonsr[0];
console.log('alpha1'+ datjsn);
console.log('delta2'+ jsonsr);
console.log('beta'+ data23);
output of the console logs
RESULT => { count: 1,
rows:
[ orders {
dataValues: [Object],
_previousDataValues: [Object],
_changed: {},
_modelOptions: [Object],
_options: [Object],
__eagerlyLoadedAssociations: [],
isNewRecord: false } ] }
alpha1 {"count":1,"rows":[ {"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}]}
delta2 [object Object]
beta undefined
var data23 = jsonsr[0];
In here you have took wrong place. Actually the data is in jsonsr.rows[0].
For this you can use,
jsonsr.rows[0];
or if the key value is not known use the Object.keys to get the all the objects in array and proceeding with loop with the condition of check the object value in array and length greater than 0 can get the all the datas.
The object is sequelize object not just object.
Try to use .get()
var timekeep = await Orders.findAndCountAll(
{
where : {
cid : orders_info.cid,
},
order: [
['id', 'DESC']
],
limit: 1,
}
);
console.log(timekeep.rows[0].get())

for of loop is only run once

I need to traverse a pretty deep object and I need to extract 12 values in different depths. My plan was to extract with the for of the values for each depth but I have a problem in the first depth.
I am a little confused about the for of behavior.
I thought this:
for (const key of Object.keys(jsonData)){
console.log(i+1);
if (isWantedValue(key))
{
artifactColl[key] = jsonData[key];
}
console.log(key, jsonData[key]);
}
for of loop would run a cycle for each key element that it finds inside the object but the loop is only running once. It prints out all necessary keys with values in the lower console.log function but it calls isWantedValue function only once.
Can please somebody explain that to me?
Object looks like this:
{ searchNGResponse:
{ totalCount: [ '420' ],
from: [ '-1' ],
count: [ '-1' ],
tooManyResults: [ 'false' ],
collapsed: [ 'false' ],
repoDetails: [ [Object] ],
data: [ [Object] ] } }
console output:
1
called with searchNGResponse
searchNGResponse { totalCount: [ '416' ],
from: [ '-1' ],
count: [ '-1' ],
tooManyResults: [ 'false' ],
collapsed: [ 'false' ],
repoDetails: [ { 'xxx': [Object] } ],
data: [ { artifact: [Object] } ] }
Edit: updated
Your jsonData object has only one key, as the console output shows: searchNGResponse.
What you want is the keys of that object, the searchNGResponse object, specifically jsonData.searchNGResponse like this
for (const key of Object.keys(jsonData.searchNGResponse)){
console.log(i+1);
if (isWantedValue(key))
{
artifactColl[key] = jsonData.searchNGResponse[key];
}
console.log(key, jsonData.searchNGResponse[key]);
}

javascript [Object] inside my object instead of real data

I have the following js code https://repl.it/N0xy/0
I am trying to push some objects into an existing one using some functions:
mylist.push(createMyObject(item.name, item.school, item.teacher))
the result contains :
{ result: true, count: 1, items: [ [ [Object], [Object] ] ] }
instead of :
{ result: true, count: 1, items: [ { name: 'Jacky', school: 'high', teacher: 'good' },
{ name: 'Tom', school: 'college', teacher: 'bad' } ] }
how can i fix this?
thanks
You forgot to do JSON.stringify(obj) in the last statement. Everything else seems fine.
You might want to change the second last line to:
obj.items = create(); as well.
or maybe obj.items = obj.items.concat(create());
You pushed an array to obj.items in stead of the separate items. create() returns an array.
Try this:
create().forEach(function(item) {
obj.items.push(item);
});
OR
let createdItems = create();
for(item of createdItems) {
obj.items.push(item);
}
In your console.log at the end, wrap the obj in a call to JSON.stringify like this:
console.log("print my obj: ",obj);

Angular/JS: Json String to object

Have problem with converting string to object.
I'm getting from the server array of object and some of these objects contains other objects. Problem is that JS reads inner object like a string.
Data structure:
[
{
name: String("Name1"),
key: String("name1"),
value: String("some text")
},
{
name: String("Name2"),
key: String("name2"),
value: [
{
name: String("Object1"),
key: String("object1"),
value: [
{
name: String("Object1 Name3"),
key: String("object1.name3"),
value: Object()
}
]
},
{
name: String("Name4"),
key: String("name4"),
value: String()
},
]
},
{
name: String("Name5"),
key: String("name5"),
value: Number("44")
}
]
Object with Name2 contains other other object like value.
Problem that when I'm trying to display this object tree with Angular object with name ** Object1 Name3** is a string.
How I can convert all data that I'm getting from the server to OBJECT?
This object tree can have up to 5 nested objects and check value of each of them not a solution for me.

Categories