JavaScript实现对象数组与对象集合匹配并添加isExcluded属性
如何给对象集合添加对应ticker的isExcluded属性?
我有以下两个数据结构:
输入1:ticker排除状态数组
[ { "ticker": "SPR", "isExcluded": false }, { "ticker": "K", "isExcluded": false }, { "ticker": "TR:CA", "isExcluded": false }, { "ticker": "TEL:CA", "isExcluded": true } ]
输入2:ticker权重对象集合
{ "K": { "ticker": "K", "weight": 19.15 }, "SPR": { "ticker": "SPR", "weight": 34.55 }, "TEL:CA": { "ticker": "TEL:CA", "weight": 30.61 }, "TR:CA": { "ticker": "TR:CA", "weight": 15.69 } }
我需要给第二个对象集合中的每个元素添加对应ticker的isExcluded属性,且该属性要放在weight之后,预期输出如下:
{ "K": { "ticker": "K", "weight": 19.15, "isExcluded": false }, "SPR": { "ticker": "SPR", "weight": 34.55, "isExcluded": false }, "TEL:CA": { "ticker": "TEL:CA", "weight": 30.61, "isExcluded": true }, "TR:CA": { "ticker": "TR:CA", "weight": 15.69, "isExcluded": false } }
实现方案(以JavaScript为例)
步骤1:构建ticker到isExcluded的映射表
先把第一个数组转换成以ticker为键、isExcluded为值的对象,这样可以快速查找对应状态,避免重复遍历数组:
const exclusionMap = inputArray.reduce((map, item) => { map[item.ticker] = item.isExcluded; return map; }, {});
步骤2:遍历权重集合,添加isExcluded属性
遍历第二个对象集合的每个键,给每个对象追加isExcluded属性。为了保证属性顺序(weight之后紧跟isExcluded),可以通过解构原对象并重新构建新对象的方式实现:
const result = {}; for (const ticker in weightCollection) { const { weight } = weightCollection[ticker]; result[ticker] = { ticker, weight, isExcluded: exclusionMap[ticker] ?? false // 兜底处理不存在的ticker,默认设为false }; }
完整代码示例
// 输入数据 const inputArray = [ { "ticker": "SPR", "isExcluded": false }, { "ticker": "K", "isExcluded": false }, { "ticker": "TR:CA", "isExcluded": false }, { "ticker": "TEL:CA", "isExcluded": true } ]; const weightCollection = { "K": { "ticker": "K", "weight": 19.15 }, "SPR": { "ticker": "SPR", "weight": 34.55 }, "TEL:CA": { "ticker": "TEL:CA", "weight": 30.61 }, "TR:CA": { "ticker": "TR:CA", "weight": 15.69 } }; // 构建映射表 const exclusionMap = inputArray.reduce((map, item) => { map[item.ticker] = item.isExcluded; return map; }, {}); // 生成结果 const result = {}; for (const ticker in weightCollection) { const { weight } = weightCollection[ticker]; result[ticker] = { ticker, weight, isExcluded: exclusionMap[ticker] ?? false }; } console.log(JSON.stringify(result, null, 2));
内容的提问来源于stack exchange,提问作者Melanie Sigrid
相关产品推荐
相关产品推荐

