简体   繁体   English

如何替换 JSON 对象数组中某个键的所有值

[英]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.

相关问题 如何在一个键下对 JSON 数组中的所有对象的键下存在的值进行分组? - How do I group values present under a key in all objects in an array of JSON, under a single key? 如何从具有多个键的 json 对象收集数据并将所有值推送到单个键:值数组 - how to collect data from json objects with multiple keys and push all values to single key:value array 在对象数组中按特定键计算分组值 - In array of objects count grouped values by certain key 如何使用 JavaScript 中的键值处理 JSON 对象数组 - How to process JSON Array of objects using Key values in JavaScript 如何从对象数组中选择键的所有特定值 - How to select all of a particular values of key from an array of objects 如何在嵌套对象数组中查找特定键的所有值? - How to find all values of a specific key in an array of nested objects? 如何在对象数组中添加所有数字键值? - How to add all numerical key-values in array of objects? 如何在 Javascript 中的对象数组中找到特定键的所有唯一值? - How to find all unique values for specific key in array of objects in Javascript? 如何获取对象数组中特定键的所有值? - How to get all values of a specific key in array of objects? 如何通过键 select 数组中的所有对象并将它们的值相加? - How to select all objects within an array by their key and add their values together?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM