从json

时间:2018-10-24 05:03:13

标签: javascript jquery arrays json object

data:[
  { user: "2016-04-14", avg_: "13", new: "32511.20" },
  { user: "2016-04-21", avg_: "32", new: "32779.17" },
  { user: "2016-04-22", avg_: "32", new: "32898.40" },
  { user: "2016-04-23", avg_: "32", new: "32903.11" },
  { user: "2016-04-24", avg_: "32", new: "329" },
  { user: "2016-04-25", avg_: "3298", new: "32962.78" }
];

我尝试了一下,并成功删除了最后两个元素

for (var i = 1; i <= 2; i++) {
    var s = data.splice(-1, i);
    console.log(s);
}

现在,我不想重复此逻辑以删除前两个想法吗?

2 个答案:

答案 0 :(得分:2)

仅使用slice

,就可以简单地获取前两个元素以及最后一个元素而无需循环

const data = [
        {user: "2016-04-14", avg_: "13", new: "32511.20"},
        {user: "2016-04-21", avg_: "32", new: "32779.17"},
        {user: "2016-04-22", avg_: "32", new: "32898.40"},
        {user: "2016-04-23", avg_: "32", new: "32903.11"},
        {user: "2016-04-24", avg_: "32", new: "329"},
        {user: "2016-04-25", avg_: "3298", new: "32962.78"}
      ];
    
    const res = [...data.slice(0, 2), ...data.slice(-2)]
console.log(res);

或者,如果您想删除前两个,并保留其余两个,则可以这样写

const data = [
        {user: "2016-04-14", avg_: "13", new: "32511.20"},
        {user: "2016-04-21", avg_: "32", new: "32779.17"},
        {user: "2016-04-22", avg_: "32", new: "32898.40"},
        {user: "2016-04-23", avg_: "32", new: "32903.11"},
        {user: "2016-04-24", avg_: "32", new: "329"},
        {user: "2016-04-25", avg_: "3298", new: "32962.78"}
      ];
    
    const res = data.slice(2, -2)
console.log(res);

答案 1 :(得分:1)

非常简单的方法-只需调用以下函数即可:

if ($this->form_validation->run($this) == FALSE) {

            $this->load->view('front/login');

        } else {

            //enter username and password
            $username = $this->input->post('username');
            $password = $this->input->post('password');

            $this->load->model('Member_model');
            $member = $this->Member_model->checkLogin($username, $password);

            if ($member) {

                $id_member = $this->Member_model->get_member_id_from_username($username);
                $member    = $this->Member_model->get_member($id_member);

                //set session variables
                $_SESSION['id_member']   = $member->id;
                $_SESSION['logged_in']   = true;
                $_SESSION['username']    = $member->username;

                //redirect
                redirect('Member/profile');

            } else {

                print_r('User doesnt exist');                
            }
        }

然后将删除前两个元素和后两个元素。