gpt4 book ai didi

javascript - 将项目添加到数组或替换它(如果它具有相同的 ID)

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:11:30 25 4
gpt4 key购买 nike

我有这个对象数组

var source = [
{id: 1, label: "one"},
{id: 2, label: "two"},
{id: 3, label: "three"}
];

我需要添加一个项目或替换它,如果它有相同的 id

var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};

source = myFunc(new_sub);
source = myFunc(new_add);

function myFunc(obj) {
return (source.findIndex(x => x.id === obj.id) === -1) ?
source.concat(obj) : source.map((item) => {
return (item.id === obj.id) ? obj : item;
});
}

这段代码工作得很好,但是有更好的方法吗?你可以检查我的代码到这个片段:

var source = [
{id: 1, label: "one"},
{id: 2, label: "two"},
{id: 3, label: "three"}
];
var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};

source = myFunc(new_sub);
source = myFunc(new_add);

function myFunc(obj) {
return (source.findIndex(x => x.id === obj.id) === -1) ?
source.concat(obj) : source.map((item) => {
return (item.id === obj.id) ? obj : item;
});
}

//PRINT
var html = "";
source.map((item) => {
html += "<li>" + item.id + " - " + item.label + "</li>";
});
$("#resp").html(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="resp">
</ul>

最佳答案

您正在对数组进行多次传递(一次在 findIndex 中,然后一次在 concatmap 中),这是不必要的.只需一次通过即可:

function myFunc(a, obj) {
let found = false;
const result = a.map(e => {
if (!found && e.id === obj.id) {
found = true;
return obj;
} else {
return e;
}
});
if (!found) {
result.push(obj);
}
return result;
}

请注意,我将源数组作为参数传递给函数,因此它没有副作用。

var source = [
{id: 1, label: "one"},
{id: 2, label: "two"},
{id: 3, label: "three"}
];

var new_sub = {id: 1, label: "new label for one"};
var new_add = {id: 4, label: "four"};

source = myFunc(source, new_sub);
source = myFunc(source, new_add);

console.log(source);

function myFunc(a, obj) {
let found = false;
const result = a.map(e => {
if (!found && e.id === obj.id) {
found = true;
return obj;
} else {
return e;
}
});
if (!found) {
result.push(obj);
}
return result;
}

当然,如果数组很小并且您知道这是标准情况,那其实并不重要。

如果您想以(在我看来)滥用 , 运算符为代价来保持简洁:

function myFunc(a, obj) {
let found = false;
const result = a.map(e => e.id === obj.id ? (found = true, obj) : e);
if (!found) {
result.push(obj);
}
return result;
}

关于javascript - 将项目添加到数组或替换它(如果它具有相同的 ID),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com