【问题标题】:javascript object filter using user_id not return expect result使用 user_id 的 javascript 对象过滤器不返回预期结果
【发布时间】:2019-12-24 02:24:01
【问题描述】:

我有下面的对象

var total_hours = <?php echo json_encode($total_hours); ?>;



    [
      {"user_id": 2959
       "total_hours": "38"
      }
      {"user_id": 116
       "total_hours": "1"
      }
    ]

我想根据 user_id

获得 total_hours
var user = document.getElementById("user").value;

            var yahooOnly = total_hours.filter(function (entry) {
                return entry.user_id === user;
            });

            total_hours = yahooOnly;

但是无法获得所需的输出。有人可以帮助我吗?

试试这个question,但没有得到所需的输出!

【问题讨论】:

标签: javascript php arrays multidimensional-array filter


【解决方案1】:

filter() 返回一个数组。您需要对其进行索引,然后访问total_hours 属性。

您可以使用.find() 而不是.filter() 来获取对象而不是数组。

var total_hours = [{
  "user_id": 2959,
  "total_hours": "38"
}, {
  "user_id": 116,
  "total_hours": "1"
}];

var user = 2959;
var yahooOnly = total_hours.find(entry => entry.user_id == user);
var yahoo_hours = yahooOnly.total_hours;
console.log(yahoo_hours)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-11
    • 2018-09-02
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多