JS - 一个数组对象中是否包含另一个数组对象中的值

1.   改造数组结构,返回想要的结构

[
	{
		name:'小明',
		age:'18',
		address:'地址111'
	},
		{
		name:'小红',
		age:'19',
		address:'小红地址'
	},
		{
		name:'小明',
		age:'20',
		address:'地址222'
	},
		{
		name:'小明',
		age:'5',
		address:'地址333'
	},
]

//想处理成----->

[
	{
		name:小明,
		list:[{
			age:18,
			address:'地址111'
		},
		{
			age:'20',
			address:'地址222'
		},
		{
			age:'5',
			address:'地址333'
		},]
	},
	{
		name:'小红',
		list:[{
			age:'19',
			address:'小红地址'
		}]
	}
]
let arr = res.data
            let dataInfo = {};
            arr.forEach((item, index) => {
              let { name } = item;
  
              if (!dataInfo[name]) {
                dataInfo[name] = {
                  name,
                  child: []
                }
              }
              dataInfo[name].child.push(item);
            });
            let list = Object.values(dataInfo); // list 转换成功的数据

2.1  返回对应的下标

 //两个数组对象中查看 其中一个数组对象是否包含另一个数组对象中的值
      let arr = [
        {key:1,val:"张三"},
        {key:2,val:"王五"},
        {key:3,val:"李四"},
        {key:4,val:"刘超"},
        {key:5,val:"赵四"}
      ]
      let arr2 = [
        {key:1,val:"张三"},
        {key:2,val:"王五"},
        {key:6,val:"666"},
        {key:7,val:"777"},
        {key:8,val:"888"},
        {key:9,val:"999"},
      ]
      //如果能找到就返回对应的下标,如果找不到,就返回-1
      for(let i=0;i<arr.length;i++){
        const Index = arr2.findIndex((item) => {return item.key === arr[i].key})
        console.log(Index);  // 0、1、-1、-1、-1
        // 前两个数据的key值相同,打印出对应的下标 ,后面找不相同的key  输出-1
      }

2.2  返回对应的对象

//两个数组对象中查看 其中一个数组对象是否包含另一个数组对象中的值
      let arr = [
        {key:1,val:"张三"},
        {key:2,val:"王五"},
        {key:3,val:"李四"},
        {key:4,val:"刘超"},
        {key:5,val:"赵四"}
      ]
      let arr2 = [
        {key:1,val:"张三"},
        {key:2,val:"王五"},
        {key:6,val:"666"},
        {key:7,val:"777"},
        {key:8,val:"888"},
        {key:9,val:"999"},
      ]
      
      for(let task of arr){
        const itemJson = arr2.find((item)=>{return item.key === task.key});
        console.log(itemJson)
        //{key: 1, val: "张三"}
        //{key: 2, val: "王五"}
        // 3 undefined
       // 如果有相同的值那么就返回对应的对象 如果没有则返回 undefined
       }
    原文作者:Lucy-
    原文地址: https://blog.csdn.net/lm1022/article/details/121613006
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞