js 数组遍历取部分值

"data": [

    {
        "bindCardId": 4365465475,
        "cardNo": "12312431241",
        "bankName": "光大银行",
        "logo": "http://localhost/bankIcon/CEB.png",
        "singleAmount": "10000.0",
        "maxAmount": "20000.0"
    },
    {
        "bindCardId": 4365465475,
        "cardNo": "12312431241",
        "bankName": "光大银行",
        "logo": "http://localhost/bankIcon/CEB.png",
        "singleAmount": "10000.0",
        "maxAmount": "20000.0"
    }
]

上面是一个数组,现在只取bindCardId、cardNo、logo、bankName这四个值,放在一个新的数组里面,求解,谢谢大家

阅读 4k
3 个回答
var newData = data.map(item => {
    const { bindCardId, cardNo, bankName, logo } = item
    return {
        bindCardId, cardNo, bankName, logo
    }
})

下面是我写的方法,要拿哪些字段可以自己传,放在第二个参数即可

function getDataByFields(data /* :Array */, fields /* :Array */) {

    var getType = {}.toString;

    // 处理第一个参数
    if (data == null || getType.call(data) !== '[object Array]') {
        return [];
    }

    var type = {}.toString.call(fields), i, j, l1, l2, result = [];

    // 处理第二个参数
    switch (type) {
        case '[object String]': {
            fields = [fields];
            break;
        }
        case '[object Array]': {
            break;
        }
        default: {
            return [];
        }
    }

    for (i = 0, l1 = data.length; i < l1; i++) {
        result[i] = {};
        for (j = 0, l2 = fields.length; j < l2; j++) {
            data[i][fields[j]] ? result[i][fields[j]] = data[i][fields[j]] : '';
        }
    }

    return result;

}
console.log(getDataByFields(data, 'bindCardId'));
console.log(getDataByFields(data, ['bindCardId', 'cardNo', 'bankName', 'logo']));

map一下即可。

推荐问题
宣传栏