Увеличьте ключ объекта в массиве JS - PullRequest
0 голосов
/ 11 октября 2018
let $object= [
        {
            tagName: "01",
            contentID: [100, 200],
            occurrences: 2
        },
        {
            tagName: "02",
            contentID: [200, 300],
            occurrences: 2
        },
        {
            tagName: "03",
            contentID: [100, 200, 300],
            occurrences: 3
        },
        {
            tagName: "04",
            contentID: [300],
            occurrences: 1
        }];

Я хочу увеличить значение occurrences, когда tagName соответствует.Как мне увеличить occurrences значение / количество?

// let tagManagerArr = []; // global scope

for (let content of contents) {
        contentId = content.contentID;
        entityType = content.entityType;
        let tags = content.tags,
            check = false;//check gives me whether a tagName is already present in the '$object' array..
     for (let tagName of tags) {
                console.log("---------------------------------------")
                 tagManagerArr.forEach(
                     (arrayItem) => {
                         if (arrayItem.tagName === tag) {
                            check = true;
                        }
                     }
                 );

                //tagManagerArr.find(
                 //   (element) => {
                  //      if (element.tagName === tagName) {
                 //           check = true;
                  //      }
                  //  });
                if (!check) {
                    tagObject = {};
                    tagObject['tagName'] = tagName;
                    tagObject['contentID'] = [];
                    tagObject['occurrences'] = 1;

                    tagObject['contentID'].push(contentId);
                } else {
                    tagManagerArr.find(
                        (element) => {
                            if (element.tagName === tagName) {
                                if (!element.contentID.includes(contentId)) {
                                    element.contentID.push(contentId);
                                }
                                element.occurrences += 1;
                            }
                        });
                }

                tagManagerArr.push(tagObject);
            }
}

это работает нормально, но с неправильными вхождениями .. Любая подсказка?

Ответы [ 2 ]

0 голосов
/ 11 октября 2018

Используйте объект вместо.Формат данных зависит от вас - сделайте так, чтобы его было легко использовать.

let tags = {
    "01": {
       contentID: [10, 20],
       occurrences: 0
    },
    "02": {
       contentID: [10, 20],
       occurrences: 0
    }
}
// get all tag names
const tagNames = Object.keys(tags);
// increment tag value
tags["01"].occurrences++;

Update: you can sort the array as well.
Object.keys(tags).map(tagName => tags[tagName]).sort((tag1, tag2) => {
    if (tag1.occurrences > tag2.occurrences) {return -1}
    if (tag1.occurrences < tag2.occurrences) {return 1}
    return 0;
});
0 голосов
/ 11 октября 2018

Использование карты из имен тегов в свойствах будет намного проще и эффективнее:

// pick a better name
const map = new Map();

for (const content of contents) {
    for (const tagName of content.tags) {
        let tagObject = map.get(tagName);

        if (tagObject === undefined) {
            map.set(tagName, tagObject = {
                contentID: new Set(),
                occurrences: 0,
            });
        }

        tagObject.occurrences++;
        tagObject.contentID.add(content.contentID);
    }
}

Затем вы можете преобразовать ее в формат массива:

const tagManagerArr = Array.from(map,
    ([tagName, {contentID, occurrences}]) => ({
        tagName,
        contentID: Array.from(contentID),
        occurrences,
    }));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...