开发者

How to update an object property array value?

If I have an object defined as:

var myObj={};

Then, I update this object with:

myObj['fruit']=['apple', 'orange'];

Later, I would like to append "[banana, melon]" to myObj['fruit'], that's update myObj to

['apple','orange','banana','melon']

what is the most elegant way to update 'fruit' attribute value of myObj in my case? That's update array by appending开发者_开发技巧 a new array.

--------EDIT-------

I need a way to append array as one variable, not extract each element of the appended array and push. e.g. oldArray append with newArray = final array


JavaScript has a built in Array.push()

myObj["fruit"].push( 'banana', 'melon' );

There are a few ways to approach appending an array. First up, use apply() to call push with the array as individual arguments:

var toAppend = ['banana', 'melon'];
// note [].push is just getting the "push" function from an empty array
// the first argument to "apply" is the array you are pushing too, the
// second is the array containing items to append
[].push.apply( myObj["fruit"], toAppend );

Also, you could concat() the arrays, however concat doesn't modify the original array so if you have other references they might get lost:

myObj["fruit"] = myObj["fruit"].concat( toAppend );


If you don't want to push, then concat :)


I would suggest to iterate the array items that you want to push, by doing this:

var newObj = ["banana", "melon"];

for (var i in newObj)
{
   myObj['fruit'].push(newObj[i]);
}

:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜