js知道value值的一个数组,根据字典关系数据筛选出对应的text值的数组

var values = ['1','2','4'];
var data = [{value:'1',text:'清香1'},
            {value:'2',text:'清香2'},
            {value:'3',text:'清香3'},
            {value:'4',text:'清香4'},
            {value:'5',text:'清香5'},
            {value:'6',text:'清香6'}];
            
我需要得到 与values对应的text值的数组
例如:var texts = ['清香1','清香2','清香4'];

代码希望简洁,高效

阅读 5.3k
4 个回答
     var data = [{value:'1',text:'清香1'},
        {value:'2',text:'清香2'},
        {value:'3',text:'清香3'},
        {value:'4',text:'清香4'},
        {value:'5',text:'清香5'},
        {value:'6',text:'清香6'}];
     var arr = ['1','2','4']
     var arr1 = []
        data.map(e=>{
            if(arr.includes(e.value))arr1.push(e.text)
        })
        console.log(arr1)
        

clipboard.png

// 虽然已解决了,我也提供一种方案:用filter过滤,再用map。 includes 是ES7的,可以用indexOf替代。
var data = [{value:'1',text:'清香1'},
    {value:'2',text:'清香2'},
    {value:'3',text:'清香3'},
    {value:'4',text:'清香4'},
    {value:'5',text:'清香5'},
    {value:'6',text:'清香6'}];
var arr = ['1','2','4']
var result = data.filter(e=>{
    return arr.includes(e.value)
}).map(el => el.text);
console.log(result); // ["清香1", "清香2", "清香4"]
var data = [{ value: '1', text: '清香1' },
  { value: '2', text: '清香2' },
  { value: '3', text: '清香3' },
  { value: '4', text: '清香4' },
  { value: '5', text: '清香5' },
  { value: '6', text: '清香6' }];
  var arr = ['1', '2', '4']
  let newArr=data.reduce((prev,cur)=>{
    arr.includes(cur.value)&&prev.push(cur.text)
    return prev
  },[])
  console.log(newArr); //(3) ["清香1", "清香2", "清香4"]
function test() {
  var values = ['1','2','4'];
  var data = [{value:'1',text:'清香1'},
            {value:'2',text:'清香2'},
            {value:'3',text:'清香3'},
            {value:'4',text:'清香4'},
            {value:'5',text:'清香5'},
            {value:'6',text:'清香6'}];
  let result = new Map(data.map(key=>[key.value, key.text]))

  let temp = new Set()
  values.map((item)=>{
    if (result.has(item)) {
      temp.add(result.get(item))
    }
  })
  return [...temp.values()]
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏