[英]Add property and copy array of objects into an nested objects
I would like to copy an array of objects in a nested object with new property.我想在具有新属性的嵌套对象中复制一组对象。 How can I use es6 to achieve something like this
我如何使用 es6 来实现这样的事情
I would like to copy:我想复制:
['cat', 'Dog', 'monkey'] into
[{"text":"cat"},{"text":"Dog","extraClasses":["ti-extra"]}, {"text":"monkey"}]
Use Array#map
, and you can test for the items that should be different so the extra props can be added to them.使用
Array#map
,您可以测试应该不同的项目,以便可以向它们添加额外的道具。
const input = ['cat', 'Dog', 'monkey'], output = input.map( text => text === "Dog" ? ({text, "extraClasses":["ti-extra"]}) : ({text}) ); console.log( output ); //[{"text":"cat"},{"text":"Dog","extraClasses":["ti-extra"]}, {"text":"monkey"}]
Maybe function like this where getClasses function returns classes array.也许像这样的函数,其中 getClasses 函数返回类数组。
['cat', 'Dog', 'monkey'].map((item) => {
return { text: item, extraClasses: getClasses() };
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.