简体   繁体   English

使用条件迭代数组对象

[英]Iterate over array object with condition

I want to get data from array of object with ES6 way.我想用 ES6 方式从对象数组中获取数据。

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我试图检查是否有title === 'second'然后返回它的 url 否则返回firstUrl

I know I can do it with for loop.我知道我可以用 for 循环做到这一点。 But, I want it with ES6 way.但是,我想要 ES6 的方式。 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.但是,不工作,我知道这不是好方法。

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

just keep it simple like this像这样保持简单

You could take an object and assign the wanted key to the object.您可以获取一个对象并将所需的键分配给该对象。 For other default titels take default .对于其他默认名称,请使用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);

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.你可以这样做,你检查你的数组中是否有第二个项目(条件title === 'second' ),然后你要么使用它,要么回退到第一个。 if first (or second) is undefined you would get an Undefinded reference erro in line (*)如果第一个(或第二个) undefined您将在行 (*) 中得到一个Undefinded reference

 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 (*)

I would use reduce instead of other method (like map) if only one computed element is needed.如果需要一个计算元素,我会使用reduce而不是其他方法(如 map)。

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.此外,如果默认值是第一个元素,那么我会从阵列serching第二的端部开始,然后,如果它不存在,我将返回第一。

So reduceRight seems to be the best option所以reduceRight似乎是最好的选择

const data = [
    // ...
];

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

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() .假设您只想知道是否有“第二个”对象,否则使用数组的第一个元素,您可以使用.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.上面的代码在访问默认情况时会抛出错误。

You can use the ternary operator to check if second exists.您可以使用三元运算符来检查second存在。 If so, grab its URL, otherwise, fallback to first 's URL like so:如果是这样,获取它的 URL,否则,回退到first的 URL,如下所示:

With both: you get the second URL两者兼而有之:您将获得第二个 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:使用first only,您将获得first'的 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.另请注意,您需要将 URL 值括在引号中,否则它们将被称为导致错误的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM