我有一个对象
,其中包含更多我想要迭代的对象
。结构是这样的:
最终,我想创建一个数组
,其中父对象的键
指向值
在子对象的标题列中,这样我可以稍后发布到一些 PHP 脚本,即我想要:
BusinessJustification => 'titleValue'
Contract => 'titleValue'
...
但是我真的很难真正循环遍历数组。
我尝试了以下两种方法,虽然我可以循环父对象,但我似乎很难访问子对象中的值,它们只是显示为索引位置,或 undefined
分别。
for (var fields in this.postData) {
for (var columns in fields){
console.log(columns['title']);
}
}
for (var fields in this.postData) {
for (var columns in fields){
console.log(Object.entries(columns['title']));
}
}
任何帮助将不胜感激,因为我真的很摸不着头脑,并且在网上尝试了一些东西。
最佳答案
I eventually want to create an
array
where thekey
of the parent object points to thevalue
in the child object's title column.
您无法像在 PHP
中那样在 Javascript
中使用这些属性生成 数组
:中的数组>PHP
实际上是一个有序的map
。 map
是将值
关联到键
的类型。但您可以创建一个 Javascript
Object ,或 Map 。但是,我相信如果您要将数据发送到某些服务器端 PHP
脚本,那么第一个选项就是您所需要的。
我相信您正在寻找这个:
const postData = {
BusinessJustification: {blur: true, title: "business-title", valid: true},
Contact: {blur: true, title: "contact-title", valid: true},
Department: {blur: true, title: "department-title", valid: true},
}
let newObj = {};
for (const field in postData)
{
newObj[field] = postData[field].title;
}
console.log(newObj);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
关于javascript - 迭代对象的对象来创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56278466/