I have a simple array and I want to update this array with the value order:"asc" and want to delete all other order key only if type == "user" and key == "country"
const items = [
{
type: "user",
values: [
{order:"asc", key:"first_name"},
{key:"last_name"},
{key:"address"},
{key:"country"},
]
},
]
My expected result is
const items = [
{
type: "user",
values: [
{key:"first_name"},
{key:"last_name"},
{key:"address"},
{order:"asc", key:"country"},
]
},
]
I'm able to do this with map inside map. Is it possible without looping twice?
items.map(
x => { if (x.type == "user") {
x.values = x.values.map(y => {
if (y.key.includes("country")) {
y.order = "asc"
} else if (JSON.stringify(x.values).includes("country")) {
delete y.order
}
return y
})
}
return [x]
});
4 Answers 4
I think that you can do that only with double loop. I write this script but it similar to yours.
var newItems = items.map(el => {
if(el.type === "user"){
el.values = el.values.map(value => {
if(value.key === "country"){
value["order"] = "asc"
}else if(value["order"] != undefined){
delete value["order"]
}
return value
})
return el
}
})
1 Comment
{key:"country"},. If I don't have this country key, then it removes the order:asc from the item {order:"asc", key:"first_name"},. I don't want to delete order:"asc", if the values does not contains country.Logic
- Loop through
itemsarray. - Find nodes with
type"type" - From that nodes loop through
valuesarray. - Clear
"order"of nodes where key is not"country" - Add
"order"as"asc"where key is"country"
Working Fiddle
const items = [
{
type: "user",
values: [
{ order: "asc", key: "first_name" },
{ key: "last_name" },
{ key: "address" },
{ key: "country" },
]
},
];
items.filter(item => item.type === "user").forEach(item => {
item.values.filter(value => value.order === "asc").forEach(value => value.order && value.key !== "country" ? delete value.order : {});
item.values.filter(value => value.key === "country").forEach(value => value.order = "asc");
});
console.log(items);
Comments
items.filter(itm => itm.type == "user")
.map(u => {u.values.map(v => {
delete v.order
if (u.values.key == "country")
u.values.order = "asc"
})
}
);
Comments
If you don't want to delete order:"asc" if there is no country in the values array then instead of JSON.stringify(x.values).includes("country") upon every object in values you could use .find() and then only loop and delete if there is an object with key:"country":
const items = [ { type: "user", values: [ {order:"asc", key:"first_name"}, {key:"last_name"}, {key:"address"}, {key:"country"}, ] }, ]
const result = items.map(obj => {
if (obj.type === 'user') {
const country = obj.values.find(o => o.key === 'country')
if (country) {
obj.values.forEach(value => delete value.order)
country.order = 'asc'
}
}
return obj
})
console.log(result)
.as-console-wrapper{min-height:100%}
JSON.stringify(x.values)- and that call is not necessary and just adds a potential source for unwanted behavior.