ketan
ketan

Reputation: 19341

Iterate over array object with condition

I want to get data from array of object with ES6 way.

I have array object.

const data = [
  {
    title: 'first',
    description: "some desc",
    url: firstUrl,
  },
  {
    title: 'second',
    description: "some desc",
    url: secondUrl,
  },
];

I am trying to check if there is title === 'second' then return it's url else return firstUrl

I know I can do it with for loop. But, I want it with ES6 way. Any help would be greatly appreciated.

I tried:

let text = data.map((val) => { val.title === 'second' ? val.url : val.url });

But, not working and I know it's not good way.

Upvotes: 0

Views: 123

Answers (6)

user11069136
user11069136

Reputation:

const secondItem = data.find(item => item.title === 'second')
const url = secondItem ? secondItem.url || firstUrl

just keep it simple like this

Upvotes: 1

k0pernikus
k0pernikus

Reputation: 66717

Assuming you only want to know if there is a "second" object and otherwise use the first element of the array, you can make use of .find().

const secondItem = data.find(e => e.title === "second"); // secondItem will be undefined if not found
const result = secondItem ? secondItem.url : data[0].url;

You should also check for the edge case that data might be an empty array. The above code would throw an error when accessing the default case.

Upvotes: 0

asdru
asdru

Reputation: 1264

I would use reduce instead of other method (like map) if only one computed element is needed.

Also if the default is the first element, then I would start from the end of the array serching the second and then, if it is not present, I would return the first.

So reduceRight seems to be the best option

const data = [
    // ...
];

let text = data.reduceRight((prev, {title, url}, i) => {
    if(prev) {
        return prev
    }
    if(title === 'second' || i === 0) {
        return url
    }
}, null)

Upvotes: 0

Fahd Lihidheb
Fahd Lihidheb

Reputation: 710

You can do this, you check if you have a second item in your array (condition title === 'second') and then you either use it or you fallback to the first one. if first (or second) is undefined you would get an Undefinded reference erro in line (*)

const data = [
  {
    title: 'first',
    description: "some desc",
    url: 'firstUrl',
  },
  {
    title: 'second',
    description: "some desc",
    url: 'secondUrl',
  },
];

// if your order is allways first and second (0 and 1) you can do this 
// const urlObject = data[1] || data[0]
const urlObject = data.find(item => item.title === 'second') || data.find(item => item.title === 'first')

// here you have your url
console.log(urlObject.url) // line (*)

Upvotes: 1

volt
volt

Reputation: 1003

You can use the ternary operator to check if second exists. If so, grab its URL, otherwise, fallback to first's URL like so:

With both: you get the second URL

const data = [{
    title: 'first',
    description: "some desc",
    url: "firstUrl"
  },
  {
    title: 'second',
    description: "some desc",
    url: "secondUrl"
  }
];

const targetURL = data[1] ? data[1].url : data[0].url;

console.log(targetURL);

With first only, you get first's URL:

const data = [{
  title: 'first',
  description: "some desc",
  url: "firstUrl"
}];

const targetURL = data[1] ? data[1].url : data[0].url;

console.log(targetURL);

Also note that you need to wrap your URL values in quotes otherwise they're called as variables which leads to errors.

Upvotes: -1

Nina Scholz
Nina Scholz

Reputation: 386680

You could take an object and assign the wanted key to the object. For other default titels take default.

For getting a result take the wanted key or default.

const
    data = [{ title: 'first', description: "some desc", url: 'firstUrl' }, { title: 'second', description: "some desc", url: 'secondUrl' }],
    temp = data.reduce((r, { title, url }) => {
        r[title === 'second' ? title : 'default'] = url;
        return r;
    }, {});

console.log(temp.second || temp.default);

Upvotes: 1

Related Questions