简体   繁体   English

尝试将 javascript 对象转换为具有多个嵌套的数组

[英]Attempting to transform a javascript object into an array with multiple nests

I have a javascript object containing:我有一个包含以下内容的 javascript 对象:

var object =[{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0},{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0}

const keyname = ['eventHeader'];

const result = keyname.reduce((acc, date, i) => {
  acc.push([keyname, data]);
  return acc;
}, []);





                          var json_object = JSON.stringify(result);
                          document.getElementById("Object").innerHTML = json_object;
                          $('.result').append('<div id ="alert" class="alert-success"><ul class="list-group" min-width:500px><li class="list-group-item active">Result Json</li><textarea class="form-control" cols="100" rows="10">{"records:"['+json_object+'</textarea></li></div>');
                        })
                    };
                    reader.onerror = function(event) {
                      console.error("File could not be read! Code " + event.target.error.code);
                    };
                    reader.readAsBinaryString(selectedFile);
              });


        });

The output required is:所需的输出是:

{
  "records": [
    {
      "common": {
        "validTime": "20180101T121222",
        "knowledgeTime": "20180101T121222"

      },
      "eventHeader": {
        "portfolioId": "Collect Acquisition Disposition Transactions",
        "type": "EQUITY_OPEN_LONG"
      },
      "details": {
        "assetId": 12,
        "custodianAccountId": 0,
        "strategyId": 0,
        "quantity": 150,
        "cost": 5001.23,
        "contractualSettleDate": "SPECIAL",
        "commission": 2.05,
        "fee": 1.03,
        "managerId": 0,
        "basketId": 0
      }
    }

but what I am getting is nothing close as I do not understand how to splice the needed 3 array keys into the proper spots in the object.但我得到的并不接近,因为我不明白如何将所需的 3 个数组键拼接到对象中的适当位置。

If anyone could assist?如果有人可以提供帮助? The closest I have been ablo to get is to push an eventHeader key into the object - but without being able to figure out how to concat the portfolioId key value pair into it.我最接近的是将 eventHeader 键推送到对象中 - 但无法弄清楚如何将portfolioId 键值对连接到其中。 Sorry if this is too noob - but I'm really strugging to understand the language.对不起,如果这太菜了 - 但我真的很难理解语言。 I had another version where I attempted a regex replace in the stringify but that didn't work either I'm assuming I need to pull in each object row - splice in the keys followed by the key value pairs - but can't figure out splice.我有另一个版本,我尝试在 stringify 中进行正则表达式替换,但这不起作用,或者我假设我需要拉入每个对象行 - 拼接键,然后是键值对 - 但无法弄清楚拼接。

The solution is:解决办法是:

var object =[{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0},{"knowledgeTime":"20180101T235959","validTime":"20180101T235959","portfolioId":"Control","type":"EQUITY_OPEN_LONG","assetId":"A","strategyId":0,"quantity":1000,"cost":100000,"contractualSettleDate":"SPECIAL","commission":2.06,"fee":1.03,"managerId":0}];

const getObject = (array) => {
  const newArray = array.map(obj => {
    const { validTime, knowledgeTime, portfolioId, type, assetId, custodianAccountId, strategyId, quantity, cost, contractualSettleDate, commission, fee, managerId, basketId } = obj;
    const newObject = {
      common: { 
         validTime,
         knowledgeTime
      },
      eventHeader: {
        portfolioId,
        type
      },
      details: {
        assetId,
        custodianAccountId,
        strategyId,
        quantity,
        cost,
        contractualSettleDate,
        commission,
        fee,
        managerId,
        basketId
      }
    };
    return newObject;
  })
  return { records: newArray };
}
const requeiredOutput = getObject(object);
console.log(requeiredOutput);

I'm not 100% sure of what you're trying to do, but if it's what I think it is then this is a solution:我不是 100% 确定您要做什么,但如果这是我认为的那样,那么这是一个解决方案:

const sourceArray = [
  {
    knowledgeTime: '20180101T235959',
    validTime: '20180101T235959',
    portfolioId: 'Control',
    type: 'EQUITY_OPEN_LONG',
    assetId: 'A',
    strategyId: 0,
    quantity: 1000,
    cost: 100000,
    contractualSettleDate: 'SPECIAL',
    commission: 2.06,
    fee: 1.03,
    managerId: 0,
  },
  {
    knowledgeTime: '20180101T235959',
    validTime: '20180101T235959',
    portfolioId: 'Control',
    type: 'EQUITY_OPEN_LONG',
    assetId: 'A',
    strategyId: 0,
    quantity: 1000,
    cost: 100000,
    contractualSettleDate: 'SPECIAL',
    commission: 2.06,
    fee: 1.03,
    managerId: 0,
  },
];

const commonKeys = ['validTime', 'knowledgeTime'];
const eventHeaderKeys = ['portfolioId', 'type'];

function createNestedObj(obj) {
  const nestedObj = {common: {}, eventHeader: {}, details: {}};
  for (const [key, val] of Object.entries(obj)) {
    if (commonKeys.includes(key)) {
      nestedObj.common[key] = val;
    } else if (eventHeaderKeys.includes(key)) {
      nestedObj.eventHeader[key] = val;
    } else {
      nestedObj.details[key] = val;
    }
  }
  return nestedObj;
}

const output = {records: []};

for (const item of sourceArray) {
  const nestedObj = createNestedObj(item);
  output.records.push(nestedObj);
}

console.log(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM