Javascript:迭代对象数组并形成新数组

时间:2017-06-30 00:16:52

标签: javascript json loops

我想按如下方式转换以下数组:

[{'dog' : 2} {'cat' : 4} , {'chimp' : 3}] -> [{'text' : 'dog', 'size' : 2}, {'text' : 'cat', 'size' : 4}, {'text' : 'chimp', 'size' : 3}]

在伪代码中

for obj in array:
    new_obj = {'text' : obj.key, 'size' : obj.val}
    new_array.append(new_obj)
return new_array

2 个答案:

答案 0 :(得分:1)



var selected = 1

@IBAction func pickImage1(_ sender: Any) {

    let image = UIImagePickerController()
    image.delegate = self
    image.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image.allowsEditing = false
    selected = 1

    self.present(image, animated: true)
}

//Add didFinishPickingMediaWithInfo here
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        if selected == 1 {
            myImageView1.image = image
        } else {
            myImageView2.image = image
        }
    }
    else {
        //error
    }
    self.dismiss(animated: true, completion: nil)
}


@IBAction func pickImage2(_ sender: Any) {
    let image2 = UIImagePickerController()
    image2.delegate = self
    image2.sourceType = UIImagePickerControllerSourceType.photoLibrary
    image2.allowsEditing = false
    selected = 2

    self.present(image2, animated: true)
}




答案 1 :(得分:0)

嗯,这并不难,你可以使用

Array.mapObject.keys()

const newArray = oldArray.map(item => {
  const key = Object.keys(item)[0];
  // Add some guard to handle empty objects..

  return { text: key, size: item[key] };
});