简体   繁体   中英

Is possible to rewrite all values in array without for loop in javascript?

Let's suppose that we have an array (myArray) with data like this:

0: myArray
   content: 'something'
   date: '15.5.2015'
   name: 'Abc'
1: myArray
   content: 'text'
   date: '15.5.2015'
   name: 'Bla'
2: etc ...

Now for rewriting all values (into eg empty string) of one object properties in this array (for example: 'content') I would use for loop like this:

for(var i = 0; i < myArray.length; i++){
  myArray[i].content = '';
}

So result of this would be:

0: myArray
   content: ''
   date: '15.5.2015'
   name: 'Abc'
1: myArray
   content: ''
   date: '15.5.2015'
   name: 'Bla'
2: etc ...

My question is: Is possible to do same result without using loop in javascript? Something like this:

myArray[all].content.RewriteInto('');

Tnx for ideas.

Anything you do will end up looping in some fashion. However, you don't have to loop...

because we now have functional array methods! You're probably looking for map or reduce , perhaps both, since you want to transform (map) each element and/or combine them into one (reduce).

As an example, we can take your data and return a string with all of the content fields concatenated using:

 var data = [{ content: 'something', date: '15.5.2015', name: 'Abc' }, { content: 'text', date: '15.5.2015', name: 'Bla' }]; var result = data.map(function(it) { return it.content; }).join(' '); document.getElementById('r').textContent = JSON.stringify(result); 
 <pre id="r"></pre> 

To remove the content field from each item, without modifying the input, you can:

 var data = [{ content: 'something', date: '15.5.2015', name: 'Abc' }, { content: 'text', date: '15.5.2015', name: 'Bla' }]; var result = data.map(function(it) { return {date: it.date, name: it.name}; }); document.getElementById('r').textContent = JSON.stringify(result); 
 <pre id="r"></pre> 

You should look at the map function . Use it like this :

myArray.map(function (data) {
    return data.content = 'value';
}

As the first comment on your question points out you always have to use a loop, but you could monkey patch the Array using prototype like:

Array.prototype.rewriteInto = function(key, rewriteVal){
  for(var k in this){
    this[k][key] = rewriteVal;
  }
};

var testData = new Array();
testData.push({
  content: 'something',
  date: '15.5.2015',
  name: 'Abc',
});

testData.push({
  content: 'something',
  date: '15.5.2015',
  name: 'bla',
});

console.log(testData);

testData.rewriteInto('content', '');
console.log(testData);

So you don't have to rewrite the loop all the time you want to use this functionality.

See example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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