如果名称不存在,需要将对象添加到数组(js)

时间:2017-08-24 15:10:10

标签: javascript arrays

如果名称不存在,请尝试将对象添加到数组。但有共和党。 例如数组:[{day:"mo"},{day:"tu"},{day:"st"}].

如果不在数组中,则需要添加{day:we}。 所以首先需要检查{day:we}是否不在数组中,然后添加它。

结果:[{day:"mo"},{day:"tu"},{day:"we"},{day:"st"}].

for (name in result) {
            if(name !== 'mo') {
              result.push({day:'mo'});
            }
            if(name !== 'tu') {
              result.push({day:'tu'});
            }
            if(name !== 'we') {
              result.push({day:'we'});
            }
            if(name !== 'th') {
              result.push({day:'th'});
            }
            if(name !== 'fr') {
              result.push({day:'fr'});
            }
            if(name !== 'sa') {
              result.push({day:'sa'});
            }
            if(name !== 'su') {
              result.push({day:'su'});
            }
              break;
          }

4 个答案:

答案 0 :(得分:1)

您可以过滤一系列天数并检查它们是否已存在于结果中:

["mo","tu","we","th","fr","sa","su"]
  .filter( day => ! result.some(obj => obj.day === day))
  .forEach( day => {
    result.push({day});
  });

更高性能的版本:

var days = new Set( ["mo","tu","we","th","fr","sa","su"]);

result.forEach( day => days.delete(day.day));

days.forEach(day => result.push({day}));

答案 1 :(得分:1)

let days = [{day:"mo"},{day:"tu"},{day:"st"}]
let toAdd = ["mo","tu","wed","thu","fri"]

toAdd.forEach( day1 => {
	if(!days.find( day2 => day2===day1 )) days.push({day:day1})
})

console.log(days)

答案 2 :(得分:1)

您可以检查是否给出了正确的日期顺序,并在更长的日期之前插入。

function add(array, insert) {
    var days = { mo: 0, tu: 1, we: 2, th: 3, fr: 4, sa: 5, su: 6 };

    array.some(function (a, i, aa) {
        if (days[a.day] === days[insert.day]) {
            return true;
        }
        if (days[insert.day] < days[a.day]) {
            aa.splice(i, 0, insert);
            return true;
        }
    }) || array.push(insert);
}

var array = [{ day: "tu" }, { day: "sa" }];

add(array, { day: "tu" }); // no insert
console.log(array);

add(array, { day: "mo" }); // insert at the beginning
console.log(array);

add(array, { day: "we" }); // insert in the middle
console.log(array);

add(array, { day: "su" }); // insert at the end
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 3 :(得分:0)

    var a = [{day:"mo"},{day:"tu"},{day:"st"}];
    if(a.map(function(obj) { return obj.day; }).indexOf('we') == -1)
       a.push({day:'we'});
    console.log(a);