最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to update an array of object in javascript - Stack Overflow

programmeradmin5浏览0评论

say I have a variable

 data=[] 

 //this variable is an array of object like 
 data = [
     {name:'a',value:'aa'},
     {name:'b',value:'bb'}
 ]

 // the data structrue can not be changed and the initial value is empty

now I want to update the data

 function updateData(){
     if(!data.length){
         data.push(arguments)
     }
     else{
         //this parts really confuse me
     }

 }

this function must accept any number of arguments,and the order of the objects in data dose not matters update rule:

  1. update the objects value to the arguments value if they have the same name.
  2. add the arguments to the data if none of the object in data have the same name.

how to write this function?

 updateData([
     {name:'a',value:'aa'},
     {name:'b',value:'bb'}
 ])
 // expect data = [
           {name:'a',value:'aa'},
           {name:'b',value:'bb'}
           ]

 updateData([
     {name:'a',value:'aa'},
     {name:'b',value:'DD'},
     {name:'c',value:'cc'}
] )
 // expect data = [
           {name:'a',value:'aa'},
           {name:'b',value:'DD'},
           {name:'c',value:'cc'}
           ]

say I have a variable

 data=[] 

 //this variable is an array of object like 
 data = [
     {name:'a',value:'aa'},
     {name:'b',value:'bb'}
 ]

 // the data structrue can not be changed and the initial value is empty

now I want to update the data

 function updateData(){
     if(!data.length){
         data.push(arguments)
     }
     else{
         //this parts really confuse me
     }

 }

this function must accept any number of arguments,and the order of the objects in data dose not matters update rule:

  1. update the objects value to the arguments value if they have the same name.
  2. add the arguments to the data if none of the object in data have the same name.

how to write this function?

 updateData([
     {name:'a',value:'aa'},
     {name:'b',value:'bb'}
 ])
 // expect data = [
           {name:'a',value:'aa'},
           {name:'b',value:'bb'}
           ]

 updateData([
     {name:'a',value:'aa'},
     {name:'b',value:'DD'},
     {name:'c',value:'cc'}
] )
 // expect data = [
           {name:'a',value:'aa'},
           {name:'b',value:'DD'},
           {name:'c',value:'cc'}
           ]
Share Improve this question edited Jul 19, 2013 at 8:10 Hemant_Negi 2,0781 gold badge22 silver badges25 bronze badges asked Jul 19, 2013 at 7:55 paynestrikepaynestrike 4,65814 gold badges48 silver badges71 bronze badges 4
  • 7 nice homework question – Brian Commented Jul 19, 2013 at 7:58
  • you missed a ma between {name:'a',value:'aa'} and {name:'b',value:'bb'} at many places – Moazzam Khan Commented Jul 19, 2013 at 8:01
  • Its a real project question, I need to dynamiclly add jquery file upload's formData – paynestrike Commented Jul 19, 2013 at 8:03
  • How about loop through array? – Hello World Commented Jul 19, 2013 at 8:06
Add a ment  | 

4 Answers 4

Reset to default 4

Ok you might want to do something like that?

var data = [
     {name:'a',value:'aa'},
     {name:'b',value:'bb'}
 ];

 function updateData(obj){
  var objFound_bool = false;
  for (var i = 0; i < data.length; i++) {
    if(obj.name === data[i].name){
      objFound_bool = true;
      data[i].value =obj.value ;
    }
  }
  if(!objFound_bool){
    data.push(obj)
  }
 }

As Ashutosh Upadhyay suggested use a name value pair instead of an array:

var data ={};

var updateData=function(){
  var len = arguments.length,
  i=0;
  for(i=0;i<len;i++){
    data[arguments[i].name]=arguments[i].value;
  }
};
updateData(
 {name:"a",value:"22"}, 
 {name:"b",value:"2"}, 
 {name:"c",value:"3"}, 
 {name:"a",value:"1"} // the new value for a
);
for(key in data){
  if(data.hasOwnProperty(key)){
    console.log(key + "=" + data[key]);
  }
}

Just read your ment about the array, so if you have to have an array you can:

var data = [];
function findIndex(name){
  var i = 0;
  for(i=0;i<data.length;i++){
    if(data[i].name===name){
      return i;
    }
  }
  return i;
}
function updateData(){
  var i = 0;
  for(i=0;i<arguments.length;i++){
    data[findIndex(arguments[i].name)]=arguments[i];
  }
}
updateData(
 {name:"a",value:"22"}, 
 {name:"b",value:"2"}, 
 {name:"c",value:"3"}, 
 {name:"a",value:"1"} // the new value for a
);

console.log(data);

if names are unique you could define data as a map and just add the values using the name as key:

 var data={
     'a':'aa',
     'b':'bb'
 }

function updateData() {
   for (var i=0;i<arguments.length;i++) { //for each argument...
      for (key in arguments[i]) { //we'll put each pair (key,value) in the data
         data[key]=arguments[i][key];
      }
   }

}

EDIT: function to transform to an array

 function toArray() {
    var array=[];
    for (key in data) {
       array.push({name:key,value:data[key]});
    }
    return array;
 }

Since order doesn't really matter to you, better choice would be an object hash instead of an array. Something like

{
  'a':{name:'a', value: 'aa'}
}

This will let you search easily based on keys and you can update the hash.

You can even employ above to your situation. Convert the array into a temporary object hash as above, do necessary changes, and convert back to an array. This will be more efficient as it will save you searches through the array.

 var output_array = [];
 for (var key in obj) {
   if (obj.hasOwnProperty(key)) {
      output_array.push(obj[key]);
   }
 }
发布评论

评论列表(0)

  1. 暂无评论