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

0

3 Answers 3

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]);

Sign up to request clarification or add additional context in comments.

1 Comment

nice hack! love functional programming
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)

4 Comments

Thanks a lot guys!, worked like a charm
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]
i edited the answer accordingly, if you pass an array, you'll need includes() to find the matching eleemnt along with filter()
Yes, working perfect. ** You guys thanks for helping me out!**
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.