我有一个这样的数组:
var objectFromArray = [
{ responsibilityName: "test1" },
{ responsibilityName: "test2" },
{ responsibilityName: "test3" },
{ responsibilityName: "test4"}
]
我想从这个数组中创建一个新对象,它们应该具有相同的键。期望的结果应该是这样的:
public function upload_file_folder(){
$folder_name = $this->input->post('account_name');
if(!is_dir("uploads/gallery/".$folder_name ."/")) {
mkdir("uploads/gallery/".$folder_name ."/");
}
$target_dir = "uploads/gallery/".$folder_name ."/";
$target_file = $target_dir.$_FILES['gallery']['name'];
move_uploaded_file($_FILES['gallery']['tmp_name'],$target_file);
}
这怎么可能在js?
答案 0 :(得分:0)
循环遍历数组并使用map
或forEach
等返回新对象。
var array = ['test1', 'test2', 'test3', 'test4']
var arr = array.map(value => {
return {responsibilityName: value};
})
console.log(arr);

答案 1 :(得分:0)
迭代数组,在另一个数组中创建对象。就这么简单。
var array = ['test1', 'test2', 'test3', 'test4']
var objectFromArray = []
array.forEach((v)=>{objectFromArray.push({"responsibilityname":v})})
答案 2 :(得分:0)
使用 array.map
并将值分配给对象
<强>样本强>
var array = ['test1', 'test2', 'test3', 'test4'];
var result = array.map(function(el) {
var obj = {};
obj['responsibilityname'] = el;
return obj;
})
console.log(array);
console.log(result);
&#13;
答案 3 :(得分:0)
根据您的评论调整:您可以使用reduce
和map
展平对象数组中的数组。
[根据您的评论修改]
const arr = [
{ responsabilityName: ['test1', 'test2', 'test3', 'test4'],
somethingElse: [1, 2, 3, 4] } ];
const arrMapped = arr
.reduce( (mappedArr, obj) =>
Object.keys(obj)
.map( key => obj[key].map( prop => ({ [key]: prop }) ) )
.reduce( (p, n) => p.concat(n), [] ),
[] );
console.log(arrMapped);