对象的属性具有值,但我尚未声明任何值

时间:2019-07-14 03:21:57

标签: javascript arrays object

我正在声明一个具有以下属性“ 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"}}]

步骤1 =此映射函数在此数组上循环

在此映射函数内部有一个简单的for循环,该循环从下一个索引而不是当前索引开始循环

在for循环内,它们是for in循环,该循环遍历map函数中当前元素的custCss属性中的所有css属性,并检查该属性是否在数组中存在的下一个css属性中可用

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"
      }
    }];

1 个答案:

答案 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());