在JavaScript中返回一个重复对象值的实例

时间:2018-05-04 03:35:51

标签: javascript arrays json object get

我正在从large API返回包含重复对象值的信息。我有一个程序名称数组和一个函数,可以找到我想要的标题。但是,我只希望它们返回一次而不是多次。

//...
var data = JSON.parse(request.responseText);
const lateNightHosts = ['The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live'];

for (x in data){
  let title = data[x]._embedded.show.name;

  function getShow() 
    if (lateNightHosts.indexOf(title) !== -1){
      console.log(title)
    } 
  }

  getShow()
}

由于未来的日程安排,API很大,因此console.log会多次返回标题。我想把它归还一次。提前致谢

3 个答案:

答案 0 :(得分:1)

您可以将所有标题添加到数组中,然后对其进行过滤

const lateNightHosts = ['The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live', 'The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live', 'The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live', 'The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live'];

filteredArray = lateNightHosts.filter(function(item, pos) {
    return lateNightHosts.indexOf(item) == pos;
})

console.log(filteredArray)

此外,您可以使用Set,因为它只包含唯一元素,然后使用spread运算符将其转换为数组

const lateNightHosts = ['The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live', 'The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live', 'The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live', 'The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live'];

var set = new Set(lateNightHosts);
var filteredArray = [...set];
console.log(filteredArray);

答案 1 :(得分:1)

你可以这样做:

var data = JSON.parse(request.responseText);
const lateNightHosts = ['The Late Show with Stephen Colbert', 'Conan', 'Jimmy Kimmel Live'];
const displayed = new Set();

for (x in data){
  let title = data[x]._embedded.show.name;

  function getShow() 
    if (lateNightHosts.indexOf(title) !== -1) {
      if (!displayed.has(title)) {
        console.log(title);
        displayed.add(title);
      }
    } 
  }

  getShow();
}

答案 2 :(得分:1)

这看起来是利用新ES6 Set数据结构的好地方。 Set只会添加唯一值,并在其原型上有多个函数,允许您访问和改变数据。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

let store = new Set();
for (x in data){
  store.add(data[x]._embedded.show.name);
}

这个新结构是可迭代的,有一个size属性,还有几个方便的原型函数,比如has(),delete()和clear()。



let target = document.getElementById('data-target');

let set = new Set();
for(let i = 0; i < 10; i++){
    set.add(`value-${i}`);
}
let elem = '';
set.forEach((value) => {
    elem += `<div>${value}</div>`;
});

target.innerHTML = elem;
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <div id="data-target"></div>
        
</body>
</html>
&#13;
&#13;
&#13;