[英]How to substitute all values of a certain key in an array of JSON objects
I have an array of JSON object, for example, people
with data, for example:我有JSON对象的阵列,例如,
people
用的数据,例如:
[
{
name : 'John',
age : '7'
},
{
name : 'Mary',
age : '70'
},
{
name : 'Joe',
age : '40'
},
{
name : 'Jenny',
age : '4'
}
]
I want to substitute all string values in age
for its corresponding integer in order to sort by age
.我想将
age
所有字符串值替换为其相应的整数,以便按age
排序。 Or to add a key, for example ageI
with the integer value.或者添加一个键,例如带有整数值的
ageI
。
I could loop through the array, but, is there a better way to do that, for example with one command in jQuery?我可以遍历数组,但是,有没有更好的方法来做到这一点,例如使用 jQuery 中的一个命令?
You can use forEach
to modify the array
in place:您可以使用
forEach
就地修改array
:
var array = [ { name : 'John', age : '7' }, { name : 'Mary', age : '70' }, { name : 'Joe', age : '40' }, { name : 'Jenny', age : '4' } ] array.forEach(obj => { obj.age = Number(obj.age) }); console.log(array);
Or use map
to make a new array:或者使用
map
创建一个新数组:
var array = [ { name : 'John', age : '7' }, { name : 'Mary', age : '70' }, { name : 'Joe', age : '40' }, { name : 'Jenny', age : '4' } ] console.log( array.map(obj => ({ name: obj.name, age: Number(obj.age) })) );
If you just want to sort, simply sort with a callback如果你只是想排序,只需用回调排序
arr.sort((a,b) => parseInt(a.age, 10) - parseInt(b.age, 10));
If you want the values to stay ints, use a simple loop如果您希望值保持整数,请使用简单的循环
arr.forEach(e => e.age = parseInt(e.age, 10));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.