我正在声明一个具有以下属性“ selectorText”和“ custCss”的对象,并且我仅在声明中声明了selectorText属性的值,而custCss属性却是空对象,因为我正在声明但在下一个之后如果我在控制台上记录了变量的值,则该行将在custCss属性内显示一些css属性。
let array = [{
selectorText: "a.classname , #textfield",
custCss: {
'background-color': "yellow",
color: "white"
}
}, {
selectorText: "a.classname , #textfield",
custCss: {
'background-color': "yellow"
}
}, {
selectorText: "a.classname , #textfield",
custCss: {
'background-color': "yellow"
}
}];
let arr = array.map(function(val, idx) {
let styleObject = {
selectorText: val.selectorText,
custCss: {}
};
if (idx === array.length - 1) {
styleObject.custCss = val.custCss;
return styleObject;
}
for (let index = idx + 1; index < array.length; index++) {
(function(indx) {
for (var prop in val.custCss) {
if (array[indx].custCss.hasOwnProperty(prop) === false) {
styleObject.custCss[prop] = val.custCss[prop];
}
}
})(index);
}
// console.log(newObj)
return styleObject;
});
console.log(arr)
此函数的作用是将具有这样结构的对象映射到其rr上
[{selectorText: "a.classname , #textfield",custCss: {background-color: "yello",color: "white"}},{selectorText: "a.classname , #textfield",custCss: {background-color: "yello"}},{selectorText: "a.classname , textfield",custCss: {background-color: "yello"}}]
if the background-color present custCss object in the index 0 and also it is present in index 1 or 2 or later then we are not setting this property to the styleObject custCss property. If a css property like color which is only presnet in the first index and not in the later index then we append this into the styleObject;
这段代码基本上是从custCss中删除重复字段,并且仅保留最新的css属性,并保留数组的原始结构---
[{
selectorText: "a.classname , #textfield",
custCss: {
color: "white"
}
}, {
selectorText: "a.classname , #textfield",
custCss: {
}
}, {
selectorText: "a.classname , #textfield",
custCss: {
'background-color': "yellow"
}
}];
答案 0 :(得分:0)
短代码-
创建keys
数组。遍历数组元素,获取custCss
的键,检查它是否已经存在于keys
数组中,如果是,则删除该属性。
let arr = [{
selectorText: "some Class name",
custCss: {}
}, {
selectorText: "some class name",
custCss: {
border: "1px"
}
}];
const keys = [];
arr.reverse().forEach(({custCss}) => {
const objKeys = Object.keys(custCss);
objKeys.forEach((key) => {
if (keys.includes(key)) {
delete custCss[key];
}
});
keys.push(...objKeys);
});
console.log(arr.reverse());