0

I'm trying to get the Object ID to store in the DB for an array of object. Any ideas?

 //Input
  var data = [{
          id: 1,
          name: 'a'
      },
      {
          id: 2,
          name: 'b'
      }
  ];

This is the Object which I'm trying to get the value of, now what I'm trying to achieve is from name I'm trying to get the id value.

Expected Output

if the result is 'a' then I should get the value '1',

if the result is 'b' then I should get the value '2'

Anyone has any ideas to work on this.. Kindly help me guys

Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
Pradeep
  • 11
  • 6

3 Answers3

3

I would turn the array into an object, so that you can access obj[name] to get the id:

var data = [
  {id: 1, name: 'a'},
  {id: 2, name: 'b'},
  {id: 3, name: 'ccc'}
];
const obj = data.reduce((a, { id, name }) => {
  a[name] = id;
  return a;
}, {});
console.log(obj.a);
console.log(obj.b);

// if the name is in a variable:

const name = 'ccc';
console.log(obj[name]);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

you can use .find() :

var arr = [{
    id: 1,
    name: 'a'
  },
  {
    id: 2,
    name: 'b'
  }
];

function getId(data, name) {
  return typeof name === 'string' ?
    data.find(e => name === e.name).id :
    data.filter(e => name.includes(e.name)).map(e => e.id)
}

var result1 = getId(arr, ['a', 'b']);
var result2 = getId(arr, 'a');

console.log(result1)
console.log(result2)
Taki
  • 17,320
  • 4
  • 26
  • 47
  • 1
    **Thanks a lot guys!**, worked like a charm – Pradeep Jul 09 '18 at 06:01
  • and I have a one more question what if the string value in array like let say `var arr = ['a', 'b'];` `data.find(e => e.name === arr);` can the result be : [1, 2] – Pradeep Jul 09 '18 at 06:02
  • i edited the answer accordingly, if you pass an array, you'll need `includes()` to find the matching eleemnt along with `filter()` – Taki Jul 09 '18 at 06:15
  • Yes, working perfect. ** You guys thanks for helping me out!** – Pradeep Jul 09 '18 at 06:24
0

Try this

var data = [{
          id: 1,
          name: 'a'
      },
      {
          id: 2,
          name: 'b'
      }
  ];

var valuse = data.find(function (el) {
  return el.name == 'b' ;
});


console.log(valuse.id);
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33