如何将数组添加到现有Javascript对象的新键?

时间:2018-02-21 17:19:23

标签: javascript ecmascript-6

这是我的完整功能,它来自React-Native项目,使用redux并使用axios和redux-thunk进行ajax调用:

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 })

        }
      );
  }
}

在map函数中,这是记录格式:

{
  id: 521,
  date: "2014-04-16T16:24:04",
  date_gmt: "2014-04-16T16:24:04",
  modified: "2018-01-12T23:58:22"
}

这是完成后的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"}
]

如何将data_json添加到每条记录?

谢谢!

1 个答案:

答案 0 :(得分:0)

我可以通过将asignment更新为:

来实现
record.gallery = JSON.parse(data_json);

这是一个简单的改变,但我想通过评论中指出的内容:

  

原始对象不是JSON对象,而是普通的javascript   对象