首页 > 解决方案 > 用JS中现有数组的一些值创建一个新数组

问题描述

我拥有的数组如下。我们称之为数组reduction

var reduction = [
    {
        ReductionID: 5813,
        PatiendID: 945994,
        ProviderAcctNumber: "",
        Discharge: "945994 : 01/01/0001 - 01/01/001",
        Selected: 1,
        Balance: 20,
        Charges: 10
    }
];

我想要一个新数组 ( patientDetails),格式中只有两个值

{
   PID: 945994 // which is PatientID in the reduction array
   selection: 1// which is Selected in the reduction array
}

我在第二个数组中想要的是:

有可能与map()功能有关吗?

标签: javascriptreactjs

解决方案


你可以这样做

var arr = [{
    ReductionID:5813,
    PatientID: 945994,
    ProviderAcctNumber:"",
    Discharge: "945994 : 01/01/0001 - 01/01/001",
    Selected: 1,
    Balance: 20,
    Charges: 10
}];

var updatedArr = arr.map((obj)=>{
    return {
        PID:obj.PatientID,
        selection:obj.Selected
    }
});

console.log(updatedArr);

map在这里,我们使用并选择我们需要的值并根据需要返回对象来遍历原始数组


推荐阅读