将JavaScript对象值复制到JavaScript中的关联数组中

将JavaScript对象值复制到JavaScript中的关联数组中,javascript,Javascript,将JavaScript对象中的值转换为关联数组。下面是我尝试做的一个例子 $(window).load(function() { items = [ {title: 'Paint pots'}, {title: 'Polka dots'}, {title: 'Pebbles'} ]; var test; for(var item in items) { test=[{name:item.title}]; } for(item

将JavaScript对象中的值转换为关联数组。下面是我尝试做的一个例子

$(window).load(function() {
  items = [
    {title: 'Paint pots'},
    {title: 'Polka dots'},
    {title: 'Pebbles'}
  ];
  var test;       
  for(var item in items) {
    test=[{name:item.title}];
  }
  for(item in test) {
    alert(item.title);
  }
});
但是代码不能正常工作。有人能指出这里的错误吗



这里是指向我的小提琴的链接:

问题:您的代码正在创建一个数组数组(每个数组包含一个对象)。除了覆盖
测试
,所以它是一个单一对象数组的单一对象数组

这与代码的运行方式相同,但具有所需的效果。请注意,到最后,代码更难理解:

items = [ // array of three objects
    {title: 'Paint pots'},
    {title: 'Polka dots'},
    {title: 'Pebbles'}
];

var test = new Array(); // an array

for(var i=0; i < items.length; i++) {
    test[i]=[{name:items[i].title}];  // test[i] = an ARRAY with a single object
}                                     // which has a single property

for(var i = 0; i < test.length; i++) {
    alert(test[i][0].name); // get test's i-th array's first item's name property
}
items=[//三个对象的数组
{标题:'油漆罐'},
{标题:'波尔卡圆点'},
{标题:“鹅卵石”}
];
var test=新数组();//阵列
对于(变量i=0;i

解决方案:创建对象数组(不是单元素数组):

项目=[
{标题:'油漆罐'},
{标题:'波尔卡圆点'},
{标题:“鹅卵石”}
];
var test=新数组();
对于(变量i=0;i


旁注:这不需要jQuery。

这里有一些导致问题的错误

var检验--您没有初始化
测试

for(项目中的变量项)
——每个
项目
这里有一个键,所以它是0,1,2。它不是一些人所期望的items数组中的项

test=[{name:item.title}]
--您在这里覆盖测试变量,而不是将项添加到数组中,或者(如果您打算这样做的话)将
项.title
分配给
名称

用于(测试中的项目)
——与之前一样,此处的
项目
不是对象,而是键

[编辑,在我前面的回答中合并,并进行一些编辑]

代码片段的开头(
$(window.load
)表示您正在使用jQuery,因此我将在jQuery对象上使用
每个
函数*

$(document).ready(function() {
  items = [
    {title: 'Paint pots'},
    {title: 'Polka dots'},
    {title: 'Pebbles'}
  ];
  var test = []; /* initialize as array */
  $.each(items, function(idx, item) 
  {
    test.push({name:item.title}); /* add to array rather than overwrite */
  })
  $.each(test, function(idx, item) {
    console.log(item.name); /* use console instead of alert, because we're not savages */
  })
});


(*有些浏览器确实支持一个
用于每个(对象中的变量)
构造,但现在是。一个
用于(对象的变量)

我认为javascirpt中没有什么比关联数组更好的了。我说得对吗?…代码执行后,
测试
不是一个单一属性对象吗?@zerkms:很抱歉。但我仍然没有定义。@PrashantShilimkar well对象是关联数组
{key1:'value1',key2:'value2'}
(至少如果使用一个键可以容纳一个值的定义)@MacleanPinto:your
已经是数组了。对象数组。很抱歉响应太晚。您消除了我对关联数组的许多误解。我会接受这个答案,因为它指出了我的错误,而不是直接提供解决方案。@MacleanPinto感谢您的评论。根据你的建议,我把我的答案合并起来了。
$(document).ready(function() {
  items = [
    {title: 'Paint pots'},
    {title: 'Polka dots'},
    {title: 'Pebbles'}
  ];
  var test = []; /* initialize as array */
  $.each(items, function(idx, item) 
  {
    test.push({name:item.title}); /* add to array rather than overwrite */
  })
  $.each(test, function(idx, item) {
    console.log(item.name); /* use console instead of alert, because we're not savages */
  })
});