[英]Create new property into an object depending to the value of another one
对于像这样的对象数组:
myArray = [
{id: "1", type: "xxx"},
{id: "2", type: "abc"},
{id: "3", type: "xxx"},
{id: "4", type: "yyy"}
];
如果需要为每个受type
值影响的对象创建另一个属性,例如:
如果type === xxx
则newProp = prop1
如果type === abc
则newProp = prop2
如果type === yyy
则newProp = prop3
结果数组应如下所示:
myArray = [
{id: "1", type: "xxx", newProp: "prop1"},
{id: "2", type: "abc", newProp: "prop2"},
{id: "3", type: "xxx", newProp: "prop1"},
{id: "4", type: "yyy", newProp: "prop3"}
];
我用for循环和很多if语句做了它,但可能有一个我不知道的更有效的解决方案。
有任何想法吗?
您可以使用所需的类型值来获取对象。
var myArray = [{ id: "1", type: "xxx" }, { id: "2", type: "abc" }, { id: "3", type: "xxx" }, { id: "4", type: "yyy" }]; myArray.forEach(o => o.newProp = { xxx: 'prop1', abc: 'prop2', yyy: 'prop3' }[o.type]); console.log(myArray);
使用包含其中一个类型时要添加的值的映射。 然后,您可以map
数组并返回一个新对象,其中添加了适当的值作为newProp
:
const map = { xxx: 'prop1', abc: 'prop2', yyy: 'prop3' }; const myArray = [{id: "1", type: "xxx"}, {id: "2", type: "abc"}, {id: "3", type: "xxx"}, {id: "4", type: "yyy"}]; const out = myArray.map(obj => { return { ...obj, newProp: map[obj.type] }; }); console.log(out)
如果您正在寻找功能性的js-one-liner,请点击此处:
// type2Prop is a object lookup table for type to newProp values
myArray.map(e => (v => v && (e.newProp = v))(type2Prop[e.type]))
注意:它还处理这种情况,如果type
与已知类型中的任何type
不匹配,则不会添加属性。
使用map
:
let myArray = [{id: "1", type: "xxx"},{id: "2", type: "abc"},{id: "3", type: "xxx"},{id: "4", type: "yyy"}]; let resp = myArray.map(x => { if(x.type === 'xxx') x.newProp = 'prop1'; if(x.type === 'abc') x.newProp = 'prop2'; if(x.type === 'yyy') x.newProp = 'prop3'; return x; }) console.log(resp);
您可以这样做,并在需要时添加其他类型:
const myArray = [ {id: "1", type: "xxx"}, {id: "2", type: "abc"}, {id: "3", type: "xxx"}, {id: "4", type: "yyy"} ]; const types = { "xxx": "prop1", "abc": "prop2", "yyy": "prop3", }; const newArray = myArray.map(e=>{ return {...e, newProp: types[e.type]}; }); console.log(newArray);
for(const el of myArray)
el.newProp = {"xxx" : "prop1", "abc": "prop2" /*...*/ }[el.type];
使用Array的map()
尝试以下内容:
var myArray = [ {id: "1", type: "xxx"}, {id: "2", type: "abc"}, {id: "3", type: "xxx"}, {id: "4", type: "yyy"} ]; myArray = myArray.map(function(i){ if(i.type==='xxx') i.newProp='prop1' else if(i.type==='abc') i.newProp='prop2' else if(i.type==='yyy') i.newProp='prop3' return i; }); console.log(myArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.