[英]How to add array to new key of existing Javascript object?
here is my full function, it is from a React-Native project using redux and making a ajax call with axios and redux-thunk:这是我的完整功能,它来自使用 redux 并使用 axios 和 redux-thunk 进行 ajax 调用的 React-Native 项目:
export function FetchEtiquetas() {
return function (dispatch) {
axios.get( url )
.then(response => {
response.data.map( record =>
{
axios.get('https://e.dgyd.com.ar/wp-json/wp/v2/media?_embed&parent='+record.id)
.then(response => {
// compose the new json string with each post gallery
let data_json = '[';
response.data.map( record =>
data_json = data_json + '{ "title": "' + record.title.rendered + '", "subtitle": "'+ record.caption.rendered.slice(3, -5) + '", "illustration": "' + record.source_url + '"},'
);
data_json = data_json.slice(0, -1)+"]"; // removes last comma
record.gallery = date_json;
console.log("date_json record.gallery: "+record.gallery);
})
.catch(error => {
console.log(error.response)
});
console.log("gallery in data action: "+record.gallery);
}
);
dispatch({ type: FETCH_ETIQUETAS_SUCCESS, payload: response.data })
}
);
}
}
In the map function, this is the record format:在 map 函数中,这是记录格式:
{
id: 521,
date: "2014-04-16T16:24:04",
date_gmt: "2014-04-16T16:24:04",
modified: "2018-01-12T23:58:22"
}
and this is the data_json format once it completed:这是完成后的 data_json 格式:
[
{ "title": "img6", "subtitle": "", "illustration": "domain.com/img6.jpg"},
{ "title": "img7", "subtitle": "", "illustration": "domain.com/img7.jpg"},
{ "title": "img8", "subtitle": "", "illustration": "domain.com/img8.jpg"}
]
How can I add data_json to each record?如何将 data_json 添加到每条记录?
thanks!谢谢!
I could do it by updating the asignment to:我可以通过将分配更新为:
record.gallery = JSON.parse(data_json);
It was a simple change but I figured it out thanks to what was pointed out in the comments:这是一个简单的更改,但由于评论中指出的内容,我弄清楚了:
The original object is not a JSON object, but a plain javascript object.
原始对象不是 JSON 对象,而是普通的 javascript 对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.