[英]Converting Javascript Multidimensional Array format
我有一个看起来像这样的数组-
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将输出我想要的内容,但是返回值将输出为undefined,这使我感到困惑。
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; } });
您可以将所需属性作为对象映射到新对象中。
它与
Array#map
数组的对象, field
的新对象,以及另一个具有重命名属性的对象, Object.assign
和传播语法...
var data = [{ 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 }], result = Object.assign( ...data.map(({ id, helperTitle: title, helperText: text }) => ({ ['field_' + id]: { title, text } })) ); console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
我猜所有的处理都应该在$ .get函数中:
$.getJSON('/api/system/formHelperText/4', function (data) {
var myNewArray = data.map(function(item) {
var obj = {};
obj['field_' + item.id] = { Title: item.helperTitle, Text: item.helperText };
return obj;
});
console.log(myNewArray);
};
您可以编写一个简单的reduce
调用以获得所需的输出:
const array=[{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}] const result= array.reduce((acc, a) => (acc[a.form_field_name] = {title: a.helperTitle,text: a.helperText}, acc), {}); console.log(result);
答案很简单:
const objs = new Map();
for (const obj of myOldArray) {
objs.set(obj.form_field_name, obj);
}
现在,您可以通过字段名称访问对象:
const myObj = objs.get("field_1");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.