基于内部对象属性值的数组操作?

时间:2018-10-10 20:12:17

标签: javascript arrays javascript-objects

我正在使用wordpressAPI来检索信息并将其显示在javascript应用程序中。我想知道基于返回的对象中的数据操作数组的正确方法。例如:

我得到的数据是一个包含3个对象的数组:

data = [{...}, {...}, {...}]

对象包含如下数据:

{ id: 1234, slug: 'slug-name', status: 'published' }

..还有更多。但是我想知道的是如何遍历每个对象并检查slug ==='slug-name-2',如果是,我想将整个对象及其所有信息移至数据数组的开始。

3 个答案:

答案 0 :(得分:0)

这是做到这一点的一种方式

//find index of the slug-name-2
let index = data.findIndex((x => x.slug === 'slug-name-2');
//get object
let slug = data[index];
//remove from current location
data.splice(index)
//add it to the beginning
data.unshift(slug);

我敢肯定,可以提出100多种方法,也许是更有效的方法。

看看Array.Prototype methods,那里有很多东西,您可以结合使用几种方法并以多种方式操纵数组。

答案 1 :(得分:0)

您可以根据条状字符串sort对其进行操作。

let data = [
  { id: 1234, slug: 'slug-name', status: 'published' },
  { id: 1235, slug: 'slug-name-1', status: 'published' },
  { id: 1236, slug: 'slug-name-2', status: 'published' },
  { id: 9999, slug: 'slug-name-2', status: 'published' },
  { id: 1237, slug: 'hello', status: 'published' }
];

let sortedData = data.sort((a, b) => b.slug.indexOf('slug-name-2') - a.slug.indexOf('slug-name-2'));
console.log(sortedData);

答案 2 :(得分:0)

您可以通过许多不同的方式执行此操作,一种方式是对给定键和值上的数组进行“伪排序”:

const input = [
  { id: 1234, slug: 'slug-name-0', status: 'published' },  
  { id: 1234, slug: 'slug-name-1', status: 'published' },
  { id: 1234, slug: 'slug-name-2', status: 'published' },
  { id: 1234, slug: 'slug-name-3', status: 'published' },
  { id: 1234, slug: 'slug-name-4', status: 'published' }
]

const output = input.sort((a, b) => {
  if (b.slug === 'slug-name-2') return 1;
  return 0;
})

console.log(output);

相关问题