【发布时间】:2019-01-01 10:09:13
【问题描述】:
我有一个看起来像这样的数组 -
var myOldArray = [{
"id": 1,
"form_id": 4,
"form_field_name": "field_1",
"helperTitle": "This is Box 1's TItle",
"helperText": "This is Box 1 data",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"form_id": 4,
"form_field_name": "field_2",
"helperTitle": "Box 2 Title",
"helperText": "Box 2 TExt",
"created_at": null,
"updated_at": null
}
]
我需要复制/复制/转换/...无论如何...该数组是这样的 -
myNewArray = {
field_1['title'] = "This is Box 1's Title",
field_1['text'] = "This is Box 1 data",
field_2['title'] = "Box 2 Title",
field_2['text'] = "Box 2 Text",
}
这样我可以参考它
console.log(myNewArray.field_1.title)
或更有用的东西。
我尝试使用过滤方法无济于事。我尝试的一切都返回未定义。我只是超级困惑。有没有更好的方法直接引用子数组中的元素而不进行转换?
这有点工作...... console.log 会输出我想要的,但返回的值会输出为未定义,这让我很困惑。
myOldArray = [{
"id": 1,
"form_id": 4,
"form_field_name": "field_1",
"helperTitle": "This is Box 1's TItle",
"helperText": "This is Box 1 data",
"created_at": null,
"updated_at": null
},
{
"id": 2,
"form_id": 4,
"form_field_name": "field_2",
"helperTitle": "Box 2 Title",
"helperText": "Box 2 TExt",
"created_at": null,
"updated_at": null
}
]
var AR = myOldArray;
var newArr = AR.filter(function(item) {
if (item.form_field_name == fieldName) {
console.log('txt - ' + item + '\n\n');
return item;
}
});
【问题讨论】:
-
发布的问题似乎根本没有包含any attempt 来解决问题。 StackOverflow 期待您 try to solve your own problem first,因为您的尝试有助于我们更好地了解您想要什么。请编辑问题以显示您尝试过的内容,以说明您遇到minimal reproducible example 的特定障碍。欲了解更多信息,请参阅How to Ask 并拨打tour。
-
顺便说一句,您的
myNewArray应该是一个对象而不是数组,因为您使用命名属性而不是键。 -
是的,我以为我在 myNewArray 上使用了花括号,但我已经尝试解决这个问题 6 个小时了...开始累了...我修好了。
-
myOldArray[0].helperTitle有什么问题(或不可用)? -
输出时不知道需要哪个数组索引。我需要引用特定的索引 - IE,我需要为 form_field_name = field_2 的索引输出 helperTitle,我不知道这是索引 0 还是 1,或者该数组中可能有 100 个项目。
标签: javascript arrays object multidimensional-array