[英]How to update values of each object in the array of objects in Javascript?
I have an array having multiple objects: 我有一个包含多个对象的数组:
[ {col:1} {col:1} {col:1} {col:3} {col:3} {col:9} {col:12} {col:13} ]
I want to update this array such that col having values 1 will remain same while the next value (here 3) should become 2 and then next value(here 9) should become 3 and so on.. 我想更新此数组,以使具有值1的col保持不变,而下一个值(此处为3)应变为2,然后下一个值(此处为9)应变为3,依此类推。
O/P: O / P:
[ {col:1} {col:1} {col:1} {col:2} {col:2} {col:3} {col:4} {col:5} ]
Please help. 请帮忙。
Here is a fairly simple method: 这是一个相当简单的方法:
var arr = [ {col:1}, {col:1}, {col:1}, {col:3}, {col:3}, {col:9}, {col:12}, {col:13} ]; var current = 0; var prevEl = -1; for (var i = 0; i < arr.length; i++) { var el = arr[i].col; arr[i].col = el > prevEl ? ++current : current; prevEl = el; } console.log(arr);
You can reduce your array: 您可以减少数组:
var data = [
{ col: 1 }, { col: 1 },
{ col: 1 }, { col: 3 },
{ col: 3 }, { col: 9 },
{ col: 12 }, { col: 13 }
];
var result = data.reduce(function(r, i) {
r.previous !== i.col && r.newValue++;
r.previous = i.col;
r.arr.push({ col: r.newValue });
return r;
}, {arr: [], newValue: 0}).arr;
console.log(result);
I suppose your array is sorted by col
, otherwise you need to sort it first. 我想您的数组是按
col
排序的,否则您需要先对其进行排序。
Should do what is needed. 应该做所需要的。 Doesn't rely on any specific order in original array and assumes will always start at
1
不依赖原始数组中的任何特定顺序,并假设将始终从
1
开始
var data=[ {col:1} ,{col:1} ,{col:1} ,{col:3} ,{col:3}, {col:9} ,{col:12} ,{col:13} ]; var uniqueValues = data.reduce(function(a,c){ if(a.indexOf(c.col)===-1) { a.push(c.col); } return a; },[]).sort(function(a,b){ return ab; }); // produces [1,3,9,12,13] var res=data.map(function(item){ // use index of current col value from unique values .. plus one item.col=uniqueValues.indexOf(item.col) + 1; return item; }); document.getElementById('pre').innerHTML = JSON.stringify(res,null,4)
<pre id="pre">
Edit: if lowest col isn't 1
can still use uniqueValues.indexOf(item.col) + uniqueValues [0]
编辑:如果最低col不是
1
,仍然可以使用uniqueValues.indexOf(item.col) + uniqueValues [0]
You could run a for
loop to iterate through your array, and have if clauses to check for certain values; 您可以运行一个
for
循环来遍历数组,并使用if子句检查某些值。 say the array object is called myArray
: 说数组对象称为
myArray
:
var myArray = [ {col:1} {col:1} {col:1} {col:3} {col:3} {col:9} {col:12} {col:13} ];
for ( var i = 0; i < myArray.length; i++){
if ( myArray[i] === 3 ){
myArray[i] = 2;
}
// and so on.....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.