我有这样的对象数组
<?php
namespace App\Normalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use App\Entity\Event;
class EventNormalizer implements NormalizerInterface {
private $normalizer;
public function __construct(ObjectNormalizer $normalizer){
$this->normalizer = $normalizer;
}
public function normalize($event, $format = null, array $context = [])
{
$data = $this->normalizer->normalize($event, $format, $context);
return $data;
}
public function supportsNormalization($data, $format = null, array $context = [])
{
return $data instanceof Event;
}
}
我要做的就是用newArray = [3,4]的多数量参数来获得这样的结果
[ { id: 2,
name: 'woda',
price: 45.98,
quantity: 1,
createdAt: 2019-07-23T17:50:43.033Z,
updatedAt: 2019-07-23T17:50:43.033Z,
shopId: 2 },
{ id: 3,
name: 'sham',
price: 69.98,
quantity: 1,
createdAt: 2019-07-23T17:50:43.033Z,
updatedAt: 2019-07-23T17:50:43.033Z,
shopId: 2 } ]
答案 0 :(得分:0)
如果要通过数组的相同索引处的数字更新数组的每个索引,则简单的for循环非常有用。但是如果mult
比数组短
var arr = [ { id: 2,
name: 'woda',
price: 45.98,
quantity: 1,
createdAt: '2019-07-23T17:50:43.033Z',
updatedAt: '2019-07-23T17:50:43.033Z',
shopId: 2 },
{ id: 3,
name: 'sham',
price: 69.98,
quantity: 1,
createdAt: '2019-07-23T17:50:43.033Z',
updatedAt: '2019-07-23T17:50:43.033Z',
shopId: 2 } ];
var mult = [3,4];
for (var i = 0; i<arr.length; i++) {
arr[i]['quantity'] = mult[i] * arr[i]['quantity'];
}
console.log(arr);
答案 1 :(得分:0)
var arr=[ { id: 2,
name: 'woda',
price: 45.98,
quantity: 1,
createdAt: "2019-07-23T17:50:43.033Z",
updatedAt: "2019-07-23T17:50:43.033Z",
shopId: 2 },
{ id: 3,
name: 'sham',
price: 69.98,
quantity: 1,
createdAt: "2019-07-23T17:50:43.033Z",
updatedAt: "2019-07-23T17:50:43.033Z",
shopId: 2 } ]
function sometingCool(arr,multipleByThisArr){
var i=0;
return arr.map(x=>{
x.quantity=x.quantity*multipleByThisArr[i];
i++;
return x;
})
}
console.log(sometingCool(arr,[3,4]))
答案 2 :(得分:0)
执行此操作有两种选择。首选是使用map
运算符:
let fooArray = [ { id: 2,
name: 'woda',
price: 45.98,
quantity: 1,
createdAt: '2019-07-23T17:50:43.033Z',
updatedAt: '2019-07-23T17:50:43.033Z',
shopId: 2 },
{ id: 3,
name: 'sham',
price: 69.98,
quantity: 1,
createdAt: '2019-07-23T17:50:43.033Z',
updatedAt: '2019-07-23T17:50:43.033Z',
shopId: 2 } ];
let newArray = [3,4];
使用destructuring assignment和...rest运算符(当您要使用嵌套对象时,这种方式会很有用):
fooArray = fooArray.map(({
quantity,
...rest
}, i) => ({ ...rest, quantity : quantity * newArray[i]}));
console.log(fooArray);
或更简单,更易读的map()
函数,没有...rest
运算符和破坏性分配:
fooArray = fooArray.map((f,i) => {
f.quantity = f.quantity * newArray[i]
return f;
});
console.log(fooArray);
,第二种方法是使用foreach
方法。正如Cerbrus所建议的那样,因为它在语义上更好,代码更短,只想编辑一个值时更容易理解:
fooArray.forEach((e, i) => {
e.quantity = e.quantity * newArray[i];
})
console.log(fooArray);
使用什么取决于您。我们只是展示了您可以实现所需的方法。