Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
160
rated 0 times [  166] [ 6]  / answers: 1 / hits: 56435  / 11 Years ago, fri, july 19, 2013, 12:00:00

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'}
]

More From » arrays

 Answers
8

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 comment 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);

[#76886] Thursday, July 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nikokorbinm

Total Points: 744
Total Questions: 126
Total Answers: 104

Location: Jersey
Member since Fri, Oct 1, 2021
3 Years ago
;