【问题标题】:How I can get index from each element from json and output as array如何从 json 中的每个元素获取索引并输出为数组
【发布时间】:2021-09-15 15:01:35
【问题描述】:

我有这个 json 代码:

 "genres":[{"id":28,"name":"Action"},{"id":53,"name":"Thriller"},{"id":878,"name":"Science Fiction"}]

我如何才能从每个喜欢的 Javascript 中获取 id:

['28', '53', '878']

我需要这个值来设置 select2 中的选择

$('#gen').select2().select2('val', ['28', '53', '878']);            

谢谢!

【问题讨论】:

  • $('#gen').select2().select2('val', data.genres.map(el => String(el.id)));
  • ID 必须是字符串。这对@Nick 有用吗?
  • 现在会了.. :)
  • @Nick 我写了$('#gen').select2().select2('val', json.map(el => String(el.id)));,但我只选择了第一个值,即 28 为什么?
  • 不确定。您的 JSON 结构可能有问题?你可以在这里看到它的工作原理:codesandbox.io/s/sweet-yalow-esvdh?file=/src/index.js:248-265

标签: javascript arrays json multidimensional-array


【解决方案1】:
var filter = genres.map(x => x.id)
$('#gen').select2().select2('val', filter);     

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2017-01-17
    • 2014-10-15
    • 2022-01-12
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 2014-01-21
    • 2014-03-10
    相关资源
    最近更新 更多