-2

I have an array of objects (JAVASCRIPT) like below

 [
        {
            "code": "123",
            "label": "Test123"
        },
        {
            "code": "234",
            "label": "Test"
        },
        {
            "code": "980",
            "label": "joe"
        }
    ]

And i have a string array like below

["123", "234"]

I want to loop through array of objects and pass string array to get the "label"

I am expecting an output like below

[
        {
            "code": "123",
            "label": "Test123"
        },
        {
            "code": "234",
            "label": "Test"
        }
    ]

Please let me know if there is any efficient solution (JAVASCRIPT) because my array of objects is big.

Frontend developer
  • 469
  • 1
  • 6
  • 18

2 Answers2

1

Try this:

const obj =  [
  {
    "code": "123",
    "label": "Test123"
  },
  {
    "code": "234",
    "label": "Test"
  },
  {
    "code": "980",
    "label": "joe"
  }
];

const arr = ["123", "234"];

var output = arr.flatMap(item => obj.filter(x => x.code == item));
console.log(output);
anon
  • 816
  • 5
  • 17
0

If the array is big, this can help to use Array.reduce.

const input = [{
    "code": "123",
    "label": "Test123"
  },
  {
    "code": "234",
    "label": "Test"
  },
  {
    "code": "980",
    "label": "joe"
  }
]

const input2 = ["123", "234"];

const inputObj =input.reduce((acc, cur) => {
  acc[cur.code] = cur.label;
  return acc;
}, {});

const result = input2.reduce((acc, cur) => {
  if (inputObj[cur]) {
    acc.push({
      code: cur,
      label: inputObj[cur]
    });
  }
  return acc;
}, []);
console.log(result);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39