如何在NodeJS上修改数组

时间:2019-05-05 14:43:37

标签: node.js json

这是我在模型文件中的数组,

var genres = [
  "Action",
  "Comedy",
  "Documentary"
];

我需要这样退货(重新发送)

 [
      { label: "Action", value: 1 },
      { label: "Comedy", value: 2 },
      { label: "Documentary", value: 3 },
      { label: "Drama", value: 4 }
   ];

我写了这样的请求

router.get("/genre", (req, res, next) => {
  try {
    let genre = MovieModel.genres;
    res.send(genre);
  } catch (e) {
    return res.send(e.message);
  }
});

3 个答案:

答案 0 :(得分:2)

您可以使用Array.map组成一个新数组。

router.get("/genre", (req, res, next) => {
  try {
    res.send(MovieModel.genres.map((genre, index) => { return { label: genre, value: index }; }));
  } catch (e) {
    return res.send(e.message);
  }
});

答案 1 :(得分:0)

<button type="button" class="p_2bbL9" aria-label="Next" tabindex="0" aria-describedby="TooltipContent304" disabled>
  <span class="p_2-hnq">
    <svg viewbox="0 0 20 20" class="p_v3ASA" focusable="false" aria-hidden="true">
    <path d="M17.707 9.293l-5-5a.999.999 0 1 0-1.414 1.414L14.586 9H3a1 1 0 1 0 0 2h11.586l-3.293 3.293a.999.999 0 1 0 1.414 1.414l5-5a.999.999 0 0 0 0-1.414" fill-rule="evenodd"></path>
    </svg>
  </span>
</button>

给你:

const genres = [
  "Action",
  "Comedy",
  "Documentary"
];

const newGenres = genres.map((genre, i) => {
  return (
    { "label": genre, "value": i + 1 }
  )
});

console.log(newGenres);

要通过[ { label: "Action", value: 1 }, { label: "Comedy", value: 2 }, { label: "Documentary", value: 3 }, { label: "Drama", value: 4 } ]; 返回此邮件:

res.send

答案 2 :(得分:-1)

运作良好

const arr = ["Action", "Comedy", "Documentary", "Drama"];

arr.map((arrElement, index) => ({ label: arrElement, value: index }));