javascript - How to combine two array, but take care for no same elements
问题描述
I have a simple question. Before I have look around, but the answers I find, was mostly for another situation.
I have two arrays with css-properties
old=['font-size: 12px;','color: 12px;','border-left: 1px solid red;'];
new=['font-size: 20px;','border-left: 1px solid green;','left:20px;'];
How can I combine this both arrays to have at the end an array which contains only unique styles with the properties from the "new" array if there is something change to the old ones?
In the example above, I want to have this result
result=['font-size: 20px;','color: 12px;','border-left: 1px solid green;','left:20px;'];
At the first time, I try to make a loop through the old elements, split the items at the ":" but then I see a problem about the names of the styles. If I check if "left" is inside a string it will return true on "left" but also on every other style-names which contains "left" for example margin-left, padding-left...
How I can solve it in the easiest way?
Thanks a lot.
解决方案
您可以从这两个数组中创建一个数组(最后是新项),然后创建reduce
一个由字符串中位于之前的子字符串索引的对象:
,然后获取对象的条目:
const old = ['font-size: 12px;', 'color: 12px;', 'border-left: 1px solid red;'];
const newArr = ['font-size: 20px;', 'border-left: 1px solid green;', 'left:20px;'];
const resultObj = [...old, ...newArr].reduce((a, str) => {
const [key, val] = str.split(/: ?/);
a[key] = val;
return a;
}, {});
const result = Object.entries(resultObj).map(([key, value]) => `${key}: ${value}`);
console.log(result);
请注意,这new
是一个保留字 - 它不能是变量名。
推荐阅读
- java - 在 Apache Beam PCollection 中使用 AutoValueSchema 会给出“RuntimeException:Creator 参数 arg0 与模式字段不对应”
- mysql - 简单的 SQL 查询但返回错误的结果
- amazon-web-services - IAM 用户可以自己创建另一个“子”IAM 用户吗?
- kentico - 找不到咖啡和啤酒产品部分的字段
- python - 调整熊猫数据框中的图像
- java - 添加方法java
- html - 图片没有获得移动响应
- android - setState 不会改变 TextField 的装饰
- excel - 使用 VBA 从已关闭的 Excel 工作簿中导入图像/图片
- python - 如何在点击时从模板传递值