邮递员-如何将项目添加到数组中,然后随机使用数组元素?

时间:2019-10-10 09:50:50

标签: javascript arrays json parsing postman

我有这个json

enter image description here

此JSON代表购物车 我需要将所有“ id”参数放入数组并将该数组设置为环境变量。 JSON中可以有多个“ id”参数。然后,我需要随机使用创建的数组中的元素。 (我需要根据ID从购物车中随机删除商品)

有没有办法做到这一点?我正在努力寻找解决方案。 谢谢

3 个答案:

答案 0 :(得分:0)

let order = {
    commerceItems:[
        {
            name: 'test1',
            id: 1
        },
        {
            name: 'test2',
            id: 2
        },
        {
            name: 'test3',
            id: 3
        }
    ]
};

let arr = [];

for (item of order.commerceItems) {
    arr.push(item.id);
}
console.log(arr);
  

[1、2、3]

答案 1 :(得分:0)

如果只想从对象数组中返回随机数据,则可以这样做:

let order = {
    id: "7824t70ujhfiu",
    totalCommerce: 5,
    commerceItems:[
        {
            value: 'value 1',
            anotheValue: 'another one 1',
            name: 'name 1',
            id: "iuhvue0743bg3y"
        },
        {
            value: 'value 2',
            anotheValue: 'another one 2',
            name: 'name 2',
            id: "sdhvuhsdupvhh9y470y3yg"
        },
        {
            value: 'value 3',
            anotheValue: 'another one 3',
            name: 'name 3',
            id: "o0402t207t782yt78"
        },
        {
            value: 'value 4',
            anotheValue: 'another one 4',
            name: 'name 4',
            id: "72b07t347y74y7by"
        },
        {
            value: 'value 5',
            anotheValue: 'another one 5',
            name: 'name 5',
            id: "oin98y49yb2y49y"
        }
    ]
};

pickRandom = () => {
    var arr = order.commerceItems;
    return arr[Math.floor(Math.random() *arr.length)];
}

const random_data = [pickRandom(), pickRandom()];

const filter_array = [...new Map(random_data.map(item => [item.id, item])).values()];

order = {
    ...order,
    totalCommerce: filter_array.length,
    commerceItems: filter_array 
  };

console.log(order);

答案 2 :(得分:0)

首先获得整个响应,然后将其解析。您已将该代码放在Tests的{​​{1}}标签中

enter image description here

针对您的情况:

postman

现在将var array = JSON.parse(responseBody).order.commerceItems; var ids = []; for(var i=0; i< array.length; i++) { ids.push(array[i].id); } 放在环境变量或ids的全局变量中。

PostMan

在此之后,它将看起来像这样。 enter image description here

现在,当您想从某个ID中随机访问一个ID时,您必须在postman.setEnvironmentVariable("ProductIds",JSON.stringify(ids)); 标签中编写,就像这样:

enter image description here 并在请求正文中:

enter image description here