更改对象数组中的元素

时间:2018-05-18 16:51:29

标签: javascript arrays angularjs object

我有

形式的数据
data = [
    {
        "date":"2018-05-18T-6:00:00.000Z",
        "something":"something1",
        "something":"something1"
    },
    {
       "date":"2018-05-19T-6:00:00.000Z",
       "something":"something2",
       "something":"something2"
    }
]

如何抓取对象中的第一个元素,编辑它们,然后将它们替换回对象?

所以看起来应该是这样的

 data = [
    {
        "date":"2018-05-18",
        "something":"something1",
        "something":"something1"
    }
    {
        "date":"2018-05-19",
        "something":"something2",
        "something":"something2"
    }
]

我尝试过这样的事情

var date = [];
const getSessions = () => {
 loginService.getUser().then((response) => {
  var user_id = response.data.id;
  console.log("getUser returning this => ", response.data);
  loginService.getUserSessions(user_id).then((response) => {
    $scope.sessions = response.data;

    for (var i = 0; i < $scope.sessions.length; i++){
      date.push($scope.sessions[i].next_class.slice(0,10));
  };

  $scope.sessions.push(date);
  console.log($scope.sessions);

这会缩短日期,但不会替换对象中的原始日期。

2 个答案:

答案 0 :(得分:-1)

你可以做类似的事情 -

var data = [
      {
      "date":"2018-05-18T-6:00:00.000Z",
      "something":"something1",
      },
      {
      "date":"2018-05-19T-6:00:00.000Z",
      "something":"something2"
      }
    ]

     data.forEach((record) => {
         record.date = record.date.split("T")[0]
     })

    console.log(data);

答案 1 :(得分:-1)

你也可以这样做。

data.forEach(obj => { dateIntoString = moment(obj.date).format('YYYY-MM-DDDD'); obj.date = dateIntoString; });