[英]return array value from object into array
我有一些 object 使用 JSON.stringify(data) 后它返回給我下一個 json:
[{"id":77,"image":{"id":266, "zoom_url":"https://img.jpg"},"name": "example name"}]
如果我開始過濾我的 object,添加 JSON.stringify(data, ['id','image']) 它返回我下一個 JSON,沒有zoom_url
[{"id":77,"image":{"id":266}}]
在完美的情況下,我需要返回所有下一個 JSON 視圖:
[{"id":77,"image":"https://img.jpg"}]
我該如何進行這種操作?
你不能用 arguments 到JSON.stringify()
來做到這一點,因為它所能做的就是過濾,它不能轉換結構。 所以它不能只用它的zoom_url
字符串替換image
object 的 object 值。
使用數組和 object 操作來完成。
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));
在調用JSON.stringify
之前,您可以將data
轉換為您想要的格式。
let newData = data.map(obj => {
return {
id: obj.id,
image: obj.image.zoom_url
};
});
let jsonString = JSON.stringify(newData);
我會使用 JSON.parse 字符串到數組中。 使用 array.map t 然后將 object 轉換為您想要的格式。
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);
沒有所有的解構
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.