对象条目返回未定义

时间:2019-02-21 19:37:15

标签: javascript json object

我有一个从SQL查询返回的json对象。我想在发送回前端之前过滤掉json键。如果密钥为真,请返回到我正在寻找的前端。

在我的服务器文件中,有这一行。

          let returned_data = Object.entries(queried_data[0]).forEach((key, value) => {
            return value === true ? key : null
          })
          res.json(returned_data)

这是我在SQL查询后返回的json的示例。

[{first_name: 'testing', has_apple: true, has_pear: true, has_beans: false}]

我希望returned_data拥有['has_apple', 'has_pear']。目前,我对returned_data

的定义不确定

3 个答案:

答案 0 :(得分:2)

forEach不会返回map会返回的任何内容。此外,Object.entries返回一个数组数组,因此您需要在map函数中解构该值以获取键和值。将您的代码更改为

      let returned_data = Object.entries(queried_data[0]).map(([key, value]) => {
        return value === true ? key : null
      })
      res.json(returned_data)

答案 1 :(得分:1)

正如其他答案所说,forEach()不返回任何内容,因此您必须使用map()或创建一个数组,如果为true,则将值推入该数组中

var new_data=[];
Object.entries(queried_data[0]).forEach((key, value) => {
       if( value===true){new_data.push(key)}
});
console.log(new_data);

答案 2 :(得分:0)

我认为您正在寻找

const returned_data = Object.entries(queried_data[0]).map((key, value) => {
    return value === true ? key : null
}).filter(key => {
    return key !== null
});

或者简单地

const returned_data = Object.keys(queried_data[0]).filter(key, queried_data[0][key] === true);

请勿使用forEach

相关问题