[英]Add new property to an array of objects
I have a list of entities where each entity is as follows: 我有一个实体列表,其中每个实体如下:
var entity = {
position: 'X',
varA: [{ id: 1, name: 'A1' }, { id: 2, name: 'A2' }],
varB: [{ id: 1, name: 'B1' }, { id: 2, name: 'B2' }],
varC: [{ id: 1, name: 'C1' }, { id: 2, name: 'C2' }],
}
For each entity I need to add a property 'names' that is: 对于每个实体,我需要添加一个属性“名称”:
entity.names = [varA[0].name, varB[0].name, varC[0].name];
The problem is that varA, varB or varC can in some cases be undefined or have no values. 问题是在某些情况下varA,varB或varC可能是未定义的或没有值。 So I tried:
所以我尝试了:
vm.entities.map(function(entity) {
entity.names = [entity.varA[0], entity.varB[0], entity.varC[0]].filter(e => e).map(({name:n}) => n);
return entity;
});
The expected output is: 预期的输出是:
entity.names = [ 'A1', 'B1', 'C1' ]
However, I am unable to minify my javascript due to this code line: 但是,由于以下代码行,我无法缩小我的JavaScript:
entity.names = [entity.varA[0], entity.varB[0], entity.varC[0]].filter(e => e).map(({name:n}) => n);
What am I doing wrong and is there a better way to do this? 我做错了什么,还有更好的方法吗?
You could iterate all keys of the object and take only arrays for collecting names for the new property. 您可以迭代对象的所有键,并且仅采用数组来收集新属性的名称。
For getting only one name out of the array, you could use Array#some
and exit if a name of an array is found. 为了仅从阵列中获取一个名称,可以使用
Array#some
并在找到阵列名称时退出。
var entity = { position: 'X', varA: [{ id: 1, name: 'A1' }, { id: 2, name: 'A2' }], varB: [{ id: 1, name: 'B1' }, { id: 2, name: 'B2' }], varC: [{ id: 1, name: 'C1' }, { id: 2, name: 'C2' }] }; entity.names = Object.keys(entity).reduce(function (r, k) { if (Array.isArray(entity[k])) { entity[k].some(function (o) { if (o && typeof o === 'object' && o.name) { r.push(o.name); return true; } }); } return r; }, []); console.log(entity);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.