1

我试图在 if 条件下替换对象数组中键/值条目的值(文件路径),即文件目录 Documents 中存在一个或多个文件(ios 电容器离子);否则,只返回数组不变。

数组

   const currentItems = this.data;
   const filenames = [val, val, ...];

// for 循环

   for (let filename of filenames) {

// 电容文件系统 API;承诺

    Plugins.Filesystem.stat({
      path:filename+'.jpeg',
      directory: FilesystemDirectory.Documents
    }).then((result) => {

// 返回 Documents 目录中文件的路径(简化)

      const result.uri = this.imagepath;

// 映射数组

      const newItems = this.currentItems.map(e => {

// 如果条目匹配,则设置键 'linethree' 的值

        if (e.lineone === filename) {
          return {
            ...e,
            linethree: this.imagepath
          }
        }

// 否则,返回 e 不变

        else
          return { ...e,}
      });

    }).catch( reason => {
      console.error( 'onRejected : ' + reason );
    })

}

问题:

在每次迭代中 - 文件名的文件名 - 再次映射原始数组 - 使用其原始值;因此每次迭代都会覆盖上一次迭代的变化。

如何实现每个匹配项的键“linethree”处的值条目 - e.lineone === 文件名 - 持续存在?

期望的替换:

const filenames = ["uncle"]; 

[{"lineone":"nagybácsi","linetwo":"uncle","linethree":"./assets/imgs/logo.png"}]

[{"lineone":"nagybácsi","linetwo":"uncle","linethree":"_capacitor_/var/mobile/Containers/Data/Application/D95D4DEF-A933-43F1-8507-4258475E1414/Documents/nagybácsi.jpeg "}]

4

1 回答 1

1

如果我理解得很好,你需要这样的东西:

解决方案Array#Filter,Array#SomeArray#Map

const wantedImagePath = '_capacitor_/var/mobile/Containers/Data/Application/D95D4DEF-A933-43F1-8507-4258475E1414/Documents/nagybácsi.jpeg';

const fileNames = ["uncle"];
const someData = [
{
  "lineone":"ikertestvérek; ikrek",
  "linetwo":"twins",
  "linethree":"./assets/imgs/logo.png"
},
{
  "lineone":"nagybácsi",
  "linetwo":"uncle",
  "linethree":"./assets/imgs/logo.png"
},
{
  "lineone":"nőtlen (man)",
  "linetwo":"unmarried",
  "linethree":"./assets/imgs/logo.png"
},
{
  "lineone": "bar",
  "linetwo": "foo",
  "linethree": "./some/demo/path/logo.png"
}
];

const modifed = someData.filter(x => fileNames.some(y => y === x.linetwo)).map(z => ({ ...z, linethree: wantedImagePath }));
console.log(modifed)

更新:

如果要保留当前数据并修改匹配的解决方案:

const wantedImagePath = '_capacitor_/var/mobile/Containers/Data/Application/D95D4DEF-A933-43F1-8507-4258475E1414/Documents/nagybácsi.jpeg';

const fileNames = ["uncle"];
const someData = [
{
  "lineone":"ikertestvérek; ikrek",
  "linetwo":"twins",
  "linethree":"./assets/imgs/logo.png"
},
{
  "lineone":"nagybácsi",
  "linetwo":"uncle",
  "linethree":"./assets/imgs/logo.png"
},
{
  "lineone":"nőtlen (man)",
  "linetwo":"unmarried",
  "linethree":"./assets/imgs/logo.png"
},
{
  "lineone": "bar",
  "linetwo": "foo",
  "linethree": "./some/demo/path/logo.png"
}
];

const modified = someData.map(x => {
  let match = fileNames.find(y => x.linetwo === y);
  return match !== undefined ? ({ ...x, linethree: wantedImagePath }) : x;
});

console.log(modified)

于 2018-07-24T18:28:31.070 回答