如何计算此特定对象中元素的数量

时间:2019-07-15 21:14:15

标签: vue.js laravel-5

我正在调用API,并且响应是我所期望的。但是,我想计算返回的元素数,但我做不到。我认为这是代码中的重要内容。

调用Vue组件

 select department_id, count(*) from staff group by department_id
 having count(*) = (select max(count(*)) 
                    from staff group by  department_id )

Api控制器

data(){
    return {
      messages: {}
    }
  },
loadMessages(){
      axios.get("api/messagesmenu")
        .then((data) => { this.messages = data.data})
    }

API响应的类型

public function index(){

    $messages = Message::all()->where('read_at', NULL);

    if(isset($messages)){
        foreach($messages as $message){
            $from = User::find($message->from_id);
            $message->fromPrenom = $from->first_name;
            $message->fromNom = $from->last_name;
            $message->fromImage = $from->user_image;
        }
    }else{
        $messages = [];
    }


    return $messages;
}

我想计算我获得的对象数量。如果(在vue组件中)我这样做

{"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}

返回未定义

1 个答案:

答案 0 :(得分:1)

尝试一下:

const messages = {"3":{"id":560,"from_id":2,"to_id":1,"content":"tgr","created_at":"2019-07-15 16:59:03","read_at":null,"fromPrenom":"abdel1","fromNom":"Hidalgo","fromImage":"user2-160x160.png"}}

console.log(Object.keys(messages).length) // 1

或者在您的代码中:

...
.then((data) => { 
  this.messages = data.data
  console.log(Object.keys(this.messages).length)
})