简体   繁体   English

如何对必须与特定键匹配的值和另一个数组中的相同值的数组进行foreach操作

[英]How to do a foreach for an array with values that have to match specific key and the same value from another array

I have two arrays with data from my database: 我有两个数组,其中包含数据库中的数据:

Cases array and photo's array from api: api的Cases数组和照片的数组:

{
  "cases": [{
    "id": 3,
    "photo_id": 14
  }, {
    "id": 2,
    "photo_id": 0
  }, {
    "id": 1,
    "photo_id": 13
  }],
  "photos": [{
    "id": 6,
    "file": "\/images\/1556196076cache_f50f03558d201b8eb2a9af90f0838cee.png"
  }, {
    "id": 11,
    "file": "\/images\/1556198414cache_702c216fa5a4d75d74db237ddf97b012.png"
  }, {
    "id": 12,
    "file": "\/images\/1556198946cache_702c216fa5a4d75d74db237ddf97b012.png"
  }, {
    "id": 13,
    "file": "\/images\/1556726055dewekkpot.nl_short.jpg"
  }, {
    "id": 14,
    "file": "\/images\/1556791722dewekkpot.nl_short.jpg"
  }]
}

Now if any photo_id from the cases array matches any id from the photos array with the same value, i have to extract the file key from that specific index with the matching id. 现在,如果case数组中的任何photo_id与photos数组中的任何id都具有相同的值,则必须从具有匹配id的特定索引中提取文件密钥。 And push them as a new key value pair to the cases array at the correct index. 并将它们作为新的键值对推入正确索引处的cases数组。

What i now have is the following: 我现在有以下内容:

    this.state = {
        cases: [],
        photos: [],
    };

getCases() {
    axios
        .get('/cases/api')
        .then(response => {
            this.setState({
                cases: response.data.cases,
                photos: response.data.photos,
            });
            console.log(this.state.cases);
        })
}

addPhotos() {
    var photoIds = this.state.photos.map(function (player) {
        return player.id;
    });

    var casesIds = this.state.cases.map(function (player) {
        return player.photo_id;
    });

    casesIds = casesIds.filter(function (item) {
        return photoIds.includes(item);
    });

    console.log(casesIds);


}

The output of this are the values that exists in the cases array from the photos array. 此输出是photos数组中的case数组中存在的值。

so [13, 14]. 所以[13,14]。

what should i do next? 我下一步该怎么办?

Thanks in advance! 提前致谢!

Normalise your data. 规范化您的数据。 Convert your photos array to an object with photo_id as keys, for easy access. photos数组转换为以photo_id为键的对象,以方便访问。

You could do something like the following: 您可以执行以下操作:

addPhotos() {
    var photosMap = this.state.photos.reduce(function (acc, each) {
      acc[each.id] = each; // or you could just save the corresponding filename
      return acc;
    }, {});

    var photoFiles = this.state.cases.reduce(function (acc, each) { // you could alternatively use Array.filter too.
      if (photosMap[each.photo_id]) {
        acc.push(photosMap[each.photo_id]);
      }
      return acc;
    }, []);

    console.log(photoFiles);

}

You can filter the objects as below snippet and use it to render your view. 您可以按以下代码片段过滤对象,然后使用它来呈现视图。

 const obj = { "cases": [{ "id": 3, "photo_id": 14 }, { "id": 2, "photo_id": 0 }, { "id": 1, "photo_id": 13 }], "photos": [{ "id": 6, "file": "\\/images\\/1556196076cache_f50f03558d201b8eb2a9af90f0838cee.png" }, { "id": 11, "file": "\\/images\\/1556198414cache_702c216fa5a4d75d74db237ddf97b012.png" }, { "id": 12, "file": "\\/images\\/1556198946cache_702c216fa5a4d75d74db237ddf97b012.png" }, { "id": 13, "file": "\\/images\\/1556726055dewekkpot.nl_short.jpg" }, { "id": 14, "file": "\\/images\\/1556791722dewekkpot.nl_short.jpg" }] }; const photoIds = obj.cases.reduce((acc, val) => { acc[val.photo_id] = val; return acc; }, {}); const res = obj.photos.filter(val => photoIds[val.id]); console.log(res) 

You can use Array.map() and Array.find() like this: 您可以像这样使用Array.map()Array.find()

const newCases = this.state.cases.map(({ photo_id, ...rest }) => {
  const obj = { ...rest };
  this.state.photos.find(ph => {
    if(ph.id === photo_id) {
      obj.file = ph.file;
      return true;
    }
  });
  return obj;
});

Live example: 现场示例:

 const data = { "cases": [{ "id": 3, "photo_id": 14 }, { "id": 2, "photo_id": 0 }, { "id": 1, "photo_id": 13 }], "photos": [{ "id": 6, "file": "\\/images\\/1556196076cache_f50f03558d201b8eb2a9af90f0838cee.png" }, { "id": 11, "file": "\\/images\\/1556198414cache_702c216fa5a4d75d74db237ddf97b012.png" }, { "id": 12, "file": "\\/images\\/1556198946cache_702c216fa5a4d75d74db237ddf97b012.png" }, { "id": 13, "file": "\\/images\\/1556726055dewekkpot.nl_short.jpg" }, { "id": 14, "file": "\\/images\\/1556791722dewekkpot.nl_short.jpg" }] }; const newCases = data.cases.map(({ photo_id, ...rest }) => { const obj = { ...rest }; data.photos.find(ph => { if(ph.id === photo_id) { obj.file = ph.file; return true; } }); return obj; }); console.log(newCases); 

function addPhotos(cases, photos){
    return cases.map(function (currentCase) {
            const foundPhoto = photos.find(function(currentPhoto){
                return currentPhoto.id === currentCase.photo_id;
            });
            currentCase.photo_path = foundPhoto? foundPhoto.file : "/images/blank_image.jpg";
            return currentCase;
    });
};

console.log(addPhotos(this.state.cases, this.state.photos));
//Output: [{"id":3,"photo_id":14,"photo_path":"/images/1556791722dewekkpot.nl_short.jpg"},{"id":2,"photo_id":0,"photo_path":"images/blank_image.jpg"},{"id":1,"photo_id":13,"photo_path":"/images/1556726055dewekkpot.nl_short.jpg"}]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Lodash或Underscore JS,如何基于同一对象数组中的另一个键值获取特定的键值 - Using Lodash or Underscore JS , how do I obtain a specific key value based on another key value within the same objects array 如何使用forEach从数组中获取特定值 - How to get a specific Value from an array with forEach 如何遍历对象数组匹配另一个数组中的公共元素并返回“名称”的键值 - How do I iterate over an array of objects match a common element from another array and return the key value for “name” 如何过滤对象数组并使该值与React中另一个数组的值匹配? - How do I filter through an array of objects and have that value match a value of another array in React? 如何按值对对象数组进行分组,并将结果添加到另一个在特定键上具有相同值的数组中 - How to group arrays of objects by value and add the result to another array with same value at specific key 如何检查我推入对象的对象数组是否具有来自另一个对象数组的特定键值 - How to check if an array of objects where I push into objects has a specific key value from another array of objects 如果特定键的值相同,如何将值更新为嵌套的对象数组? - How to update the value into a nested array of objects if value for specific key is same? 如何获得数组值和对象键值匹配的顺序 - How to get the array value and object key values match irrespective of the order 如何将所有具有相同键的值分组到数组中 - How to group all values that have the same key into an array 如果项目具有相同的键值,则从对象数组中删除项目 - Delete items from an array of objects if they have the same key value
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM