React Native:如何实现具有多个对象的动态键

时间:2018-11-06 07:58:50

标签: react-native

这是我尝试过的代码,

var array=[];
var list = this.state.list;

var getList = function(i){
  var add = +i + 1;
  return {
    ["value"+add]:{
      Description:list[i].Description,
      Length:list[i].Length,
      Height:list[i].Height,
      Weight:list[i].Weight,
      VolumeWeight:list[i].VolumeWeight,
      ActualWeight:list[i].ActualWeight,
    }
  }
}.bind(this)

for(var i in list){
  array.push(getList(i));
}

var dataArray = array.map(function(e){
  return JSON.stringify(e);
});

dataString = dataArray.join(",");
data1 = {
  ConsigneeBranchName:this.state.searchText,
  ConsigneeBranchCode:this.state.code,
  ConsigneeBranchFullAddress:this.state.DAddress,
  SenderBranchCode:this.state.code1,
  SenderBranchName:this.state.searchTexts,
  SenderBranchFullAddress:this.state.Address,
  CreatedByEmployeeCode:id,
  CreatedByEmployeeFullName:userName,
  jsonString:{
    JsonValues:{
      id:"MyID",
      values:dataString
    }
  }
}

但是我希望结果就是这样

var result = {
  "ConsigneeBranchName":"",
  "ConsigneeBranchCode":"",
  "ConsigneeBranchFullAddress":"",
  "SenderBranchCode":"",
  "SenderBranchName":"",
  "SenderBranchFullAddress":"",
  "CreatedByEmployeeCode":"",
  "CreatedByEmployeeFullName":"",
  "jsonString":"{
    "JsonValues": {
      "id": "MyID",
      "values": {
        "value1":{
          "Description”:"testSmarter1",
          "Length”:"60",
          "Height”:"50",
          "Weight”:"70",
          "VolumeWeight”:"75",
          "ActualWeight”:”78"
        },
        "value2:{
          "Description":"Documents",
          "Length":"120",
          "Height":"68",
          "Weight":"75",
          "VolumeWeight":"122.4",
          "ActualWeight":"123"
        },
      }
    }
  }
};

请任何人帮助我

我希望在单个对象{key1:{des:1,value:as},key2:{des:2,value:aw},key3:{des:3,value:au}内具有动态键的对象}

请问我已经尝试了很多次了

请参见下面的图片我想要这部分,在单个对象内,我可以使用动态键来连接多个对象

1 个答案:

答案 0 :(得分:0)

lodash已经具有一个名为 keyBy 的功能,您可以使用它来获得此功能。如果添加lodash在您的项目中没有意义。

我已经实现了香草JS版本。

function keyBy(array, mapperFn) {
    const resultObj = {};
    array.map(item => resultObj[mapperFn(item)] = item);
    return resultObj;
}

function arrayToObject (array, keyName = 'id') {
    return keyBy(array, function(element) {return element[keyName]});
}

API:

arrayToObject(targetArray, stringNameOfThePorpertyYouWantToUseAsKey);

用法:

const listOfUsers = [{name: 'Jenitha', reputation: 6}, {name: 'Chandan', reputation: 3}];
const mapOfUsersByName = arrayToObject(listOfUsers, 'name');