如果对象在另一个数组中具有匹配值,则反应更新对象数组
Posted
技术标签:
【中文标题】如果对象在另一个数组中具有匹配值,则反应更新对象数组【英文标题】:React Update Array of Object if Object has a matching value in another Array 【发布时间】:2020-08-06 03:05:45 【问题描述】:我正在努力让以下工作。
我有一个值数组:
const active = ['1', '3', '5']
我想将此列表与对象数组(关键用户 ID)进行比较:
[
userid: '1',
username: 'peter'
,
userid: '2',
username: 'steve'
,
userid: '3',
username: 'ted'
]
然后生成一个包含活动列的更新对象数组:
data = [
userid: '1',
username: 'peter',
active: true
,
userid: '2',
username: 'steve',
active: false
,
userid: '3',
username: 'ted',
active: true
]
以下是我所做的尝试(对不起,它太离谱了)......
Object.keys(data).map((key) =>
key.filter((userid) => data.indexOf(data.userid) => active)
)
我也看到了这个错误信息,所以对象数组需要是可扩展的:
js map Error: An error occurred while selecting the store state: Cannot add property isApproved, object is not extensible.
【问题讨论】:
【参考方案1】:const active = ['1', '3', '5']
const input = [
userid: '1',
username: 'peter'
,
userid: '2',
username: 'steve'
,
userid: '3',
username: 'ted'
];
const res = input.map(x =>
const flag = active.some(y => y === x.userid)
return
userid: x.userid,
username: x.username,
active: flag
)
console.log(res)
【讨论】:
【参考方案2】:试试这个:
const active = ['1', '3', '5'];
const users = [
userid: '1',
username: 'peter'
,
userid: '2',
username: 'steve'
,
userid: '3',
username: 'ted'
];
const data = users.map(user => (
userid: user.userid,
username: user.username,
active: active.includes(user.userid)
));
console.log(data);
【讨论】:
【参考方案3】:这里稍微改写一下你的解决方案
const active = ['1', '3', '5']
const origData = [
userid: '1',
username: 'peter'
,
userid: '2',
username: 'steve'
,
userid: '3',
username: 'ted'
]
const data = origData.map(o =>
const newObj = o;
newObj.active = active.indexOf(o.userid) > -1
return newObj;
【讨论】:
【参考方案4】:使用map
和includes
应该会简化。
const active = ["1", "3", "5"];
const users = [
userid: "1",
username: "peter"
,
userid: "2",
username: "steve"
,
userid: "3",
username: "ted"
];
const data = users.map(x => ( ...x, active: active.includes(x.userid) ));
console.log(data);
【讨论】:
以上是关于如果对象在另一个数组中具有匹配值,则反应更新对象数组的主要内容,如果未能解决你的问题,请参考以下文章
如果字符串数组中的列名在字符串数组中具有匹配的值,则获取DataRow
如果未找到值,则使用 mongoose 将对象添加到数组中,否则更新字段