简体   繁体   English

Javascript中的拆分功能不适用于对象的字符串

[英]split function in Javascript not working on string from an object

Giving this in js: 在js中给出:

let data={"vets":[{"id": 1,"lt": "6","ln": 2702,"ls": "2011-07-02T00:00:00"}]};

I want to use the split() function on the ls property. 我想在ls属性上使用split()函数。

data['vets'].ls is giving the value: "2011-07-02T00:00:00". data['vets'].ls的值是:“ 2011-07-02T00:00:00”。

I save it to a variable like this: 我将其保存到这样的变量中:

let str = data['vets'].ls;

When i run str.split('T')[0] to get only 2011-07-02 , i get an error of: 当我运行str.split('T')[0]仅获得2011-07-02 ,出现以下错误:

Uncaught TypeError: Cannot read property 'split' of null

Edit: The array i have is about 3000 items. 编辑:我拥有的数组大约是3000个项目。 I am using the map() functionn to go on all of them like this: 我正在使用map()函数来像这样继续进行所有操作:

data['vets'].map(function(vet){
   let str = vet['ls'];
   let short = str.split('T');
   vet['ls'] = short[0];
})

What can be the reason for it? 可能是什么原因呢? Thanks. 谢谢。

Try data['vets'][0].ls.split('T')[0] . 试试data['vets'][0].ls.split('T')[0]

In other words, you need to first access the first child of the data[vets] array and perform a split on its ls field. 换句话说,您需要首先访问data[vets]数组的第一个子data[vets]并对其ls字段执行split What you are doing instead, is calling split on an ls property of the array itself, which is indeed undefined . 相反,您正在对数组本身的ls属性调用split,而该属性的确是undefined

To get only the "date" part from each item: 要仅从每个项目中获取“日期”部分:

 let data = {"vets":[{"id": 1,"lt": "6","ln": 2702,"ls": "2011-07-02T00:00:00"}]}; console.log(data.vets.map(entry => entry.ls.split('T')[0])); // shorter version which does the same thing console.log(data.vets.map(({ ls }) => ls.split('T')[0])); 

To create a new array of items with modified ls fields: 要创建带有修改的ls字段的新项目数组:

 let data = {"vets":[{"id": 1,"lt": "6","ln": 2702,"ls": "2011-07-02T00:00:00"}]}; // splits every item into two variables: `ls` and `rest`. `ls` is a string, // whereas `rest` is an object containing all of the fields of the original // item. Using these variables, modified objects are created and assembled // into a new array in an immutable way (the original data is not altered) console.log(data.vets.map(({ ls, ...rest }) => ({ // replaces the `ls` field's value ls: ls.split('T')[0], // includes all the other properties untouched ...rest, }))); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM