首页 > 解决方案 > 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.

标签: javascriptjquery

解决方案


您可以从这两个数组中创建一个数组(最后是新项),然后创建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是一个保留字 - 它不能是变量名。


推荐阅读