【问题标题】:Add multiple objects into an array using JS [closed]使用JS将多个对象添加到数组中[关闭]
【发布时间】:2019-10-18 22:10:15
【问题描述】:

需要用给定的对象创建一个特定的对象数组。 现在我使用了assign对象。

这里是

var str = [{componentName: "Transformer", type: "PUB", beanName: "TransformerExtractor", state: "enabled", config: {"test":"test"}},{componentName: "DBEE", type: "PUBSUB", beanName: "DBEErExtractor", state: "enabled", config: {"test":"test"}}];

var A1 = [];

var B1 = [];

finalOutput = [];

for(i=0;i<str.length;i++){

    alert(str.length);

    var output = {};

    output.flowId = "Flow1234";

    output.flowAlias = "Flow1234";

    output.description = "Flow1234";

    output.state = "Enabled";

    A1.push(output);

    alert (A1);

    B1.push(str[i]);

    alert (B1);

    finalOutput = [A1, B1].map(o => Object.assign({}, A1, o));
}

alert (finalOutput);

return finalOutput;

您能否告诉我如何获得我的预期结果,例如 [{A1,B1(from first set of variable str),{A1,B1(from 2nd set of variable str)]

【问题讨论】:

  • 请创建一个可重现的最小示例,您的代码远非最小,因此难以阅读。
  • 你想达到A1+B1A1+C1 吗?
  • 推送对象无法获得我的预期结果
  • 好的,我明白了,这可能会有所帮助Object.assign

标签: javascript arrays json object


【解决方案1】:

从上次编辑中获取数据,您可以为要添加到新对象的数据定义一个模板对象以及数组的对象。

var data = [{ componentName: "Transformer", type: "PUB", beanName: "TransformerExtractor", state: "enabled", config: { test: "test" } },{ componentName: "DBEE", type: "PUBSUB", beanName: "DBEErExtractor", state: "enabled", config: { test: "test" } }],
    template = { flowId: "Flow1234", flowAlias: "Flow1234", description: "Flow1234", state: "Enabled" },
    result = data.map(o => Object.assign({}, template, o));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

【讨论】:

  • 感谢 Nina 的解决方案。虽然使用你的想法我得到如下 {"str1":[{"0":"flowId":"ABC100","flowAlias":"","description":"","state":"enabled", "creationDate":""},"1":"flowId":"ABC100","flowAlias":"","description":"","state":"enabled","creationDate":""}} ,{"0":"componentName":"Transformation","type":"PUBSUB","beanName":"transformer","state":"enabled","config":"{\n\"project\ ":\"testVM\",\n\"section\":\"FT\"\n}"},"1":"componentName":"testComponent","type":"PUB","beanName" :"testComponent","state":"enabled","config":"{\"testComponent\":\"testComponent\"}"}}]}
  • 看起来,你有不同的数据,然后发布。
  • 再次抱歉。我还在战斗。我在这里编辑了我的代码jsfiddle.net/e03onuxk
  • 这是一个完全不同的数据集。请张贴你所拥有的和你想要的。
  • 谢谢妮娜。这是我的代码jsfiddle.net/e03onuxk/4,预期结果将如上所示。
【解决方案2】:

如果你只想合并它们,你可以使用 lodash

data = _.merge(A1, B1)

【讨论】:

  • 遇到错误未捕获的 ReferenceError: _ is not defined
  • 您需要将 lodash 添加到您的项目中
  • 这里我不能用这个。我在这里编辑了我的代码jsfiddle.net/e03onuxk
猜你喜欢
  • 1970-01-01
  • 2017-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多