I have some object After using JSON.stringify(data) it returns me next json:
[{"id":77,"image":{"id":266, "zoom_url":"https://img.jpg"},"name": "example name"}]
if i start filter my object, adding JSON.stringify(data, ['id','image']) it returns me next JSON, without zoom_url
[{"id":77,"image":{"id":266}}]
in perfect case i need return after all next JSON view:
[{"id":77,"image":"https://img.jpg"}]
How can i do this manipulation?
You can't do this with arguments to JSON.stringify(), because all it can do is filter, it can't transform the structure. So it can't replace the object value of the image object with just its zoom_url string.
Do it with array and object operations.
let data = [{"id":77,"image":{"id":266, "zoom_url":"https://img.jpg"},"name": "example name"}];
let new_data = data.map(({id, image}) => ({id, image: image.zoom_url}));
console.log(JSON.stringify(new_data));
Before calling JSON.stringify, you can convert the data into the format you want.
let newData = data.map(obj => {
return {
id: obj.id,
image: obj.image.zoom_url
};
});
let jsonString = JSON.stringify(newData);
I would use JSON.parse the string into the array. Use array.map t then transform the object into the format you want.
const str = '[{"id":77,"image":{"id":266, "zoom_url":"https://img.jpg"},"name": "example name"}]';
const data = JSON.parse(str);
const result = data.map(({ id, image: { zoom_url } }) => ({id, image: zoom_url}));
console.log(result);
Without all the destructuring
const str = '[{"id":77,"image":{"id":266, "zoom_url":"https://img.jpg"},"name": "example name"}]';
const data = JSON.parse(str);
const result = data.map(function(item) {
const id = item.id;
const zoom_url = item.image.zoom_url;
return { id: id, image: zoom_url };
});
console.log(result);