在对象的嵌套数组中搜索字符串并设置IsCheckedIn flag = true;

时间:2019-06-04 14:28:48

标签: javascript typescript

我下面有对象数组。如果用户输入字符串'00006844763487934739',我该如何搜索此嵌套Items数组并搜索'00006844763487934739',并在匹配的地方设置isChecked in = true

enter image description here

4 个答案:

答案 0 :(得分:1)

嵌套的filter可以完成这项工作。

let data = [
	{ CustomerName: "Thomas", Items: [{ LP: "00006844763487934739", IsCheckedIn: false }] },
	{ CustomerName: "Joey", Items: [{ LP: "00006844763487934738", IsCheckedIn: false }] },
	{ CustomerName: "Robert", Items: [{ LP: "00006844763487934739", IsCheckedIn: true }] }
];

let matches = data.filter(customer => customer.Items.filter(item => item.LP === "00006844763487934739" && item.IsCheckedIn).length > 0);

console.log(matches);

答案 1 :(得分:1)

如果要直接修改数组:

function checkIn(data, LP) {
  data.forEach((entry) => {
    const matchingItem = entry.Items.find(i => i.LP === LP);
    if (matchingItem) {
      matchingItem.IsCheckedIn = true;
    }
  });

  return data;
}

您将使用它(假设data是您的数组):

checkIn(data, '00006844763487934739');

答案 2 :(得分:1)

filter创建一个新数组,因此请尝试使用foreach

let searchString = '00006844763487934739';
let data = [
    { CustomerName: "Thomas", Items: [{ LP: "00006844763487934739", IsCheckedIn: false }] },
    { CustomerName: "Joey", Items: [{ LP: "00006844763487934738", IsCheckedIn: false }] },
    { CustomerName: "Robert", Items: [{ LP: "00006844763487934739", IsCheckedIn: true }] }
  ];

data.forEach((e, i) => {
    e.Items.forEach(a => {
        if(a.LP ==searchString)
            a.IsCheckedIn = true;
    })
});

console.log(data);

答案 3 :(得分:0)

如果我理解正确,则想修改现有数组,这样就可以做到:

var data = [
  {
    Items: [
      { LP: '1', IsCheckedIn: false},
      { LP: '00006844763487934739', IsCheckedIn: false}
    ]
  },
  {
    Items: [
      { LP: '3', IsCheckedIn: false},
      { LP: '00006844763487934739', IsCheckedIn: false}
    ]
  },
  {
    Items: [
      { LP: '4', IsCheckedIn: false},
      { LP: '5', IsCheckedIn: false}
    ]
  }
];

var lookupId = '00006844763487934739';

data.flatMap(dataItem => dataItem.Items).forEach(item => item.IsCheckedIn = item.LP === lookupId);

console.log(data);