如何将对象移动到数组的开头(索引0)

时间:2019-06-25 13:33:52

标签: javascript arrays object

我如何最有效地从数组中删除特定对象并将其移至开始位置

我尝试使用常规逻辑,例如查找索引,手动拼接然后再次拼接以将对象放在顶部

farmer: [
{
id:1,
name: "name 1"
},
{
id:2,
name: "name 2"
},
{
id:3,
name: "name 3"
}
]

当我选择ID为2的农夫时,我想将其移到顶部

4 个答案:

答案 0 :(得分:1)

您可以将Array.reduce()Array.unshift()Array.push()函数一起使用,如下所示:

var farmer = [
  {id: 1, name: "name 1"},
  {id: 2, name: "name 2"},
  {id: 3, name: "name 3"}
];
var searchedId = 2;

var result = farmer.reduce(function(carry, item) {
  if (item.id === searchedId) {
     carry.unshift(item);
  } else {
     carry.push(item);
  }
  return carry;
}, []);

console.log(result);

答案 1 :(得分:1)

JavaScript标准库提供了比通过id定位元素,提取元素并插入元素更好的方法。

let myArray = [{
	id: 1
}, {
	id: 2
}, {
	id: 3
}]

function moveItemById (array, id, position) {
	let elementIndex = array.findIndex((el) => {
  	return el.id === id
  })
  if (!elementIndex) {
  	return
  }
  
  array.splice(position, 0, array.splice(elementIndex, 1)[0])
}

moveItemById(myArray, 2, 0)

答案 2 :(得分:1)

constructor(props)
{
    super(props);
    this.state = { infos: [], userId: '' };
    this.onSuccess = this.onSuccess.bind(this);
    this.onFailure = this.onFailure.bind(this);
}

componentWillMount()
{
    // Get userID from local storage, then call your API 
    AsyncStorage.getItem(YOUR_KEY)
        .then(userID=> {
            if (userID)
            {
                this.setState({ userId : userID }, () => {
                    this.getScoreFromAPI(this.onSuccess, this.onFailure); 
                });
            }
        });
}

onSuccess(data)
{
    this.setState({
        infos : data
    });
}

onFailure(err)
{
    console.warn('Error ' + err);
}

getScoreFromAPI(onSuccess, onFailure)
{
    let formData = new FormData();
    formData.append('userId', this.state.userId);
    formData.append('key', '***'); //your key

    fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
        method : 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'multipart/form-data'
        },
        body: formData
    })
    .then(res => res.json())
    .then(json => {
        onSuccess(json);
    })
    .catch(err => {
        onFailure(err);
    });
} 

答案 3 :(得分:0)

这是您的代码:

var farmer =  [
    {
		id: 1,
		name: "name 1"
	},
	{
		id: 2,
		name: "name 2"
	},
	{
		id: 3,
		name: "name 3"
	}
]


farmerNew = farmer.filter(item => item.id !== 2);
selectedFarmer = farmer.filter(item => item.id === 2)[0];
farmerNew.unshift(selectedFarmer);
farmer = farmerNew
console.log(farmer)