通过键javascript过滤数组属性对象的对象

时间:2021-05-27 04:09:39

标签: javascript

我有这个对象,我想按新闻、搞笑和体育过滤文章

<form class="form-signin" method="post" th:object="${user}"
    th:action="@{''}">
    <input type="hidden" th:name="${_csrf.parameterName}"
        th:value="${_csrf.token}" />
    <h2 class="form-signin-heading">Create New Account</h2>
    <p>
        <label for="email" class="sr-only"></label> <input type="email"
            id="email" name="email" class="form-control" placeholder="Email"
            required="" autofocus="" th:field="*{email}">
    </p>
    <p>
        <label for="username" class="sr-only"></label> <input type="text"
            id="username" name="username" class="form-control"
            placeholder="Username" required="" autofocus=""
            th:field="*{username}">
    </p>
    <p>
        <label for="password" class="sr-only"></label> <input type="password"
            id="password" name="password" class="form-control"
            placeholder="Password" required="" th:field="*{password}">
    </p>
    <p>
        <label for="confirmPassword" class="sr-only"></label> <input
            type="password" id="confirmPassword" name="confirmPassword"
            class="form-control" placeholder="Confirm Password" required=""
            th:field="*{confirmPassword}">
    </p>
    <p class="form-control">
        <input required="" type="checkbox" id="accepted-agreement"
            name="terms" placeholder="I agree to the terms of service"
            th:field="*{agreementAccepted}" class="pointer"> <label
            for="accepted-agreement" class="pointer">I agree to the terms
            of service</label>

    </p>
    <p class="form-control">
        <input type="checkbox" id="is-thirteen" name="terms"
            placeholder="I am 13 years or older" th:field="*{thirteen}"
            class="pointer"> <label data-toggle="tooltip"
            data-placement="bottom"
            title="You must be at least 13 years old to access this site's social media features."
            class="pointer" for="is-thirteen">I am 13 years or older</label> <a
            id="thirteen-info" class="info" href="#" data-toggle="tooltip"
            data-bs-toggle="tooltip" data-bs-placement="bottom"
            title="You must be at least 13 years old to access this site's social media features (<a target='_blank' href='../terms#coppa'>Learn More</a>).">?</a>
    </p>
    <button class="btn btn-lg btn-primary btn-block" type="submit">Sign
        Up</button>
</form>

我想过滤以获得结果

const articles = {
article_1: {
 
tags: ['news', 'funny']
},
article_2: {
tags: ['sports', 'funny']
}
}

2 个答案:

答案 0 :(得分:0)

您可以使用 Object.entriesreduceforEach 轻松实现此结果。

const articles = {
  article_1: {
    tags: ["news", "funny"],
  },
  article_2: {
    tags: ["sports", "funny"],
  },
};

function groupArticlesByTag(obj) {
  return Object.entries(obj).reduce((acc, [key, val]) => {

    val.tags.forEach((tag) => {
      if (acc[tag]) {
        acc[tag].push(key);
      } else {
        acc[tag] = [key];
      }
    });

    return acc;
  }, {});
}

const articlesByTag = groupArticlesByTag(articles);
console.log(articlesByTag);

您甚至可以使用 Logical nullish assignment (??=)

将其缩短一点

const articles = {
  article_1: {
    tags: ["news", "funny"],
  },
  article_2: {
    tags: ["sports", "funny"],
  },
};

function groupArticlesByTag(obj) {
  return Object.entries(obj).reduce((acc, [key, val]) => {

    val.tags.forEach((tag) => {
      (acc[tag] ??= []).push(key);
    });

    return acc;
  }, {});
}

const articlesByTag = groupArticlesByTag(articles);
console.log(articlesByTag);

答案 1 :(得分:-1)

Object.keys() -> 给出一个对象的所有键的数组。

.forEach() -> 遍历项目数组

如果key已经存在则push到数组中,否则用key创建一个长度为1的数组。

let groupArticlesByTag = (articles) => {
   let articlesMap = {};
  Object.keys(articles).map((x) => {
    articles[x].tags.forEach((y)=> { 
      if(articlesMap[y]==undefined){
        articlesMap[y] = [x]
      }
      else{
        articlesMap[y].push(x);
      }
    });
  });
  return articlesMap;
}


相关问题