简体   繁体   English

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

[英]Array manipulation based on inner object property value?

I am working with the wordpressAPI to retrieve information and display it in a javascript application. 我正在使用wordpressAPI来检索信息并将其显示在javascript应用程序中。 I would like to know the proper way to manipulate an array based on the data in the returned objects. 我想知道基于返回的对象中的数据操作数组的正确方法。 For example: 例如:

Data I get back is an array containing 3 objects: 我得到的数据是一个包含3个对象的数组:

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

The objects contain data like: 这些对象包含如下数据:

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

..and much more. ..以及更多。 But what I would like to know is how to loop over each object and check for slug === 'slug-name-2' and if it is, I want to take that whole object with all of its information and move it to the beginning of the data array. 但是我想知道的是如何遍历每个对象并检查slug ==='slug-name-2',如果是,我想将整个对象及其所有信息移至数据数组的开始。

Here's one way to do it 这是一种方法

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

I'm sure one can come up with 100 more ways and perhaps more efficient ones. 我敢肯定,可以提出100多种方法,也许是更有效的方法。

Look at the Array.Prototype methods , there's so many out there, you can use a combination of few and manipulate array in so many ways. 看一下Array.Prototype方法 ,那里有很多方法 ,您可以使用几种方法的组合并以多种方式操作数组。

You could sort it based on the slug string. 您可以根据条形字符串对其进行排序

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

You could do this in many different ways, one way would be to "pseudo-sort" the array on the given key and value: 您可以通过许多不同的方式执行此操作,一种方式是对给定的键和值对数组进行“伪排序”:

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

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

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