尝试创建一个对象数组,但返回一个包含空对象的数组

发布时间:2021-02-25 09:07

我是 javascript 新手,有一个我无法解决的问题。 我有一组对象,其中包含 2 个属性。我想连接属性,其中一个是键,另一个是值。

这就是我所拥有的:

[{"prefer":"code_html","rating":"5"},{"prefer":"code_css","rating":"3"}]

这就是我想要的:

[
  {
    "code_html": "5"
  },
  {
    "code_css": "3"
  }
]

我运行这个函数:

const array = [{"prefer":"code_html","rating":"5"},{"prefer":"code_css","rating":"3"}]

const result = array.map(({prefer, rating}) => ({[prefer]: rating}));

console.log(result);

但我不明白为什么它对我不起作用。 这是我得到的打印,我不明白有什么问题

[{},{},{}] 

我在 nodeJs 中使用了这段代码,也许这就是我遇到问题的原因:

exports.addUserKmeansMatchVer2 = (req, res) => {
  
  console.log("addUserKmeansMatch function filter:");
  arr = [];
  if(req.query.filterArray)
  {
    arr = [...req.query.filterArray];
    console.log("line 256" + typeof(req.query.filterArray));
    //this is print line 256object
    console.log("line 257" +arr); 
//this is works prints: line 257{"prefer":"sport_swimming","rating":"3"},{"prefer":"code_html","rating":"5"},{"prefer":"code_css","rating":"3"}
    console.log("line 258" + req.query.filterArray);
    //print exactly the same as line 257 
  }

  let onlyPreferencesAllow = [];
  arr.forEach(({prefer,rating}) => onlyPreferencesAllow.push({[prefer]: rating}));
  console.log("line 262" + JSON.stringify(onlyPreferencesAllow));
//this is NOT work prints: line 262[{},{},{}] 


        db.doc(`/match/${req.user.handle}`)
          .set("testing")
          .then(() => {
            return res.json({ message: "Details added successfully" });
          })
          .catch((err) => {
            console.error(err);
            return res.status(500).json({ error: err.code });
          });
      }
    })
  })
};

我注意到在第 257 行它为我打印没有 [] 的数组的括号,但在第 262 行它用括号 [] 打印,我不太明白

我想起了我忘记提及的事情

我通过参数获得了 req.query.filterArray。 我是这样做的:

export const makeMatchVer2 = (data) => (dispatch) => {
  dispatch({ type: LOADING_DATA });
  axios
    .get('/kmeansFilter', {
      params: {
        filterArray: data
      }
    })
    .then((res) => {
      dispatch({
        type: MAKE_MATCH,
        payload: res.data
      });
    })
    .catch((err) => {
      dispatch({
        type: MAKE_MATCH,
        payload: []
      });
    });
};

数据本身是一个数组,可能是我做错了

回答1

对我有用的解决方案: 当我将 params 中的数组发送到 api 时,我需要使用 JSON.stringify。

export const makeMatchVer2 = (data) => (dispatch) => {
  dispatch({ type: LOADING_DATA });
  axios
    .get('/kmeansFilter', {
      params: {
        filterArray: JSON.stringify(data)
      }
    })
    .then((res) => {
      dispatch({
        type: MAKE_MATCH,
        payload: res.data
      });
    })
    .catch((err) => {
      dispatch({
        type: MAKE_MATCH,
        payload: []
      });
    });
};

当我在 nodeJS 中得到答案时,我必须使用 JSON.parse

exports.addUserKmeansMatchVer2 = (req, res) => {
  
  console.log("addUserKmeansMatch function filter:");
  arr = [];
  if(req.query.filterArray)
  {
    arr = JSON.parse(req.query.filterArray);
  }

  let onlyPreferencesAllow = [];
  arr.forEach(({prefer,rating}) => onlyPreferencesAllow.push({[prefer]: rating}));
  console.log("line 262" + JSON.stringify(onlyPreferencesAllow));


        db.doc(`/match/${req.user.handle}`)
          .set("testing")
          .then(() => {
            return res.json({ message: "Details added successfully" });
          })
          .catch((err) => {
            console.error(err);
            return res.status(500).json({ error: err.code });
          });
      }
    })
  })
};