I have two variables which is an array and array of object, I want to add the value of first variable(distance) to second variable(list)
The following works fine, but I want to know if there's any other method to get some result.
let distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]
for(let i = 0; i < distance.length;i++){
let listDistance = list.map(el => {
return Object.assign({}, el, {distance:distance[i++]})
return el
});
console.log(listDistance)
}
// output [ {city : paris , distance : 100 } , {city : london , distance : 200 } , { city : barcelona , distance : 300 }]
Like this?
let distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]
list.forEach((city,i) => city.distance = distance[i])
console.log(list)
Older browsers
let distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]
list.forEach(function(city,i) { city.distance = distance[i] })
console.log(list)
If you need a new Array you can use map:
const distance = [100,200,300]
let list = [ {"city" : "paris"} , {"city" : "london"} , { "city" : "barcelona" }]
let distList = list.map((city,i) => ({ ...city, distance : distance[i]}) )
console.log(distList)
Try this:
let array1 = [100, 200, 300]
let array2 = [{ "city": "paris" }, { "city": "london" }, { "city": "barcelona" }]
let res = array2.map((value, index) => {
return { ...value, distance: array1[index] }
})
console.log(res);
const listWithDistances = list.map(
(item, index) => ({ ...item, distance: distance[index] })
)
This has the same result of your example of returning a new Array of new Objects.
Try this
for(let i = 0; i < distance.length; i++)
{
list[i].distance = distance[i];
}
Related
"course_DxhYTv2copzWyBhKo" : {
"interest" : "DxhYTv2copzWyBhKo",
"type" : "course",
"affinity" : 3
}
From Object Name "course_DxhYTv2copzWyBhKo",
I want to slice "DxhYTv2copzWyBhKo"
Using String#split:
const data = {
"course_DxhYTv2copzWyBhKo" : {
"interest" : "DxhYTv2copzWyBhKo",
"type" : "course",
"affinity" : 3
}
};
const key = Object.keys(data)[0];
const sliceAfterSubStr = "course_";
const slicedSubStr = key.split(sliceAfterSubStr)[1];
console.log(slicedSubStr);
Using String#substr:
const data = {
"course_DxhYTv2copzWyBhKo" : {
"interest" : "DxhYTv2copzWyBhKo",
"type" : "course",
"affinity" : 3
}
};
const key = Object.keys(data)[0];
const sliceAfterSubStr = "course_";
const sliceIndex = key.indexOf(sliceAfterSubStr);
const slicedSubStr = sliceIndex !== -1
? key.substr( sliceIndex + sliceAfterSubStr.length )
: undefined;
console.log(slicedSubStr);
You can use the split operation on a string. Take a look at the following code snippet.
const courses = {
"course_DxhYTv2copzWyBhKo": {
"interest": "DxhYTv2copzWyBhKo",
"type": "course",
"affinity": 3
},
"course_DSdasdnDASnoiddDs": {
"interest": "DSdasdnDASnoiddDs",
"type": "course",
"affinity": 3
}
}
console.log(Object.keys(courses).map(key => key.split("_")[1]))
I am stuck with mapping in array of objects.
Please find the below code
const array = [
{
user: "User1",
cities: ["city1", "city2", "city3"],
},
{
user: "User2",
cities: ["city2", "city3", "city4"],
},
];
let x = {};
array.map((item) => {
let user = item.user;
let cities = item.cities;
cities.map((city) => (x[city] = user));
});
Now it returns like this:
const resArray = [{ city1: "User1", city2: "User2", city3: "User2", city4: "User2" }]
I want the array like this:
const resArray = [
{ city1: ["User1"] },
{ city2: ["User1", "User2"] },
{ city3: ["User1", "User2"] },
{ city4: ["User2"] },
];
Can anyone please help me out.
Thanks
Try this
let x = {};
array.forEach((item) => {
item.cities.forEach((city) => {
x[city] = item.cities.includes(city) ? [...x[city] ? x[city] : [], item.user] : [];
});
});
You have been assigning user to city each time. Instead the x[city] should be an array and you should push the new user inside that array.
Try this,
const array = [
{
user: "User1",
cities: ["city1", "city2", "city3"],
},
{
user: "User2",
cities: ["city2", "city3", "city4"],
},
];
let x = {};
array.map((item) => {
let user = item.user;
let cities = item.cities;
cities.map((city) => {
if(x[city] && x[city].length) {
x[city].push(user);
} else{
x[city] = [user];
}
});
});
const res = Object.keys(x).map(key => { return {[key]: x[key]}});
console.log(res);
I have an array object,
const Value = [ {
"NAME" : "XCODE",
"XXXCLASS" : [ {
"V1" : "JOHN",
"V2" : "MAD"
},{
"V1" : "KIRAN",
"V2" : "TOY"
} ]
} ]
I tried it by using forEach method. i dont know, its correct way using javascript.
let arry:any = [];
let objVal:any = {};
Value.forEach((value, index) => {
value.XXXCLASS.forEach( (value, index) =>{
arry.push(value.V1);
});
value.NAME+= ":["+arry+"]";
});
What i mean, dynamically create array with name of "NAME" property with values of "V1" property values. for yours references, kindly check below format. I Need to change this below format,
const Value = {
XCODE: ['JOHN','KIRAN']
};
CODE APPRECIATED.
You can reduce the Value array to an object with NAMEs as the properties and an array of V1 names as property values.
const Value = [ {
"NAME" : "XCODE",
"XXXCLASS" : [ {
"V1" : "JOHN",
"V2" : "MAD"
},{
"V1" : "KIRAN",
"V2" : "TOY"
}]
}]
const result = {}
Value.reduce((obj, value) => {
obj[value.NAME] = value.XXXCLASS.map(xclass => (xclass.V1))
return obj
}, result)
console.log(result)
const values = [ {
"NAME" : "XCODE",
"XXXCLASS" : [ {
"V1" : "JOHN",
"V2" : "MAD"
}],
"YYYCLASS" : [{
"V1" : "KIRAN",
"V2" : "TOY"
} ]
} ]
const result = values.reduce((map, val) => {
let people = map[val.NAME] || [];
Object.keys(val).reduce((array, key) => {
if (key === 'NAME') { return array; }
if (key.includes('CLASS')) {
array.push(val[key][0].V1);
}
return array;
}, people);
map[val.NAME] = people
return map;
}, {});
console.log(result);
Just one more way to do:
const Value = [ {
"NAME" : "XCODE",
"XXXCLASS" : [ {
"V1" : "JOHN",
"V2" : "MAD"
},{
"V1" : "KIRAN",
"V2" : "TOY"
} ]
} ]
var obj = Value[0];
var res = {};
Object.values(obj).map(i=>{
if(typeof i=== "string"){
res[i] = true;
}else{
res['XCODE'] = i.map(a=>a.V1)
}
})
console.log(res)
You could take the other objects out of the items and map new object with the wanted parts.
const
data = [{ NAME: "XCODE", XXXCLASS: [{ V1: "JOHN", V2: "MAD" }, { V1: "KIRAN", V2: "TOY" }] }],
result = data.map(({ NAME, ...o }) => ({ [NAME]: Object
.values(o)
.flatMap(a => a.flatMap(({ V1 }) => V1))
}));
console.log(result);
I have an array which looks like this :
var array =
[
{
key : { id : 1 , pack : "pack 1"},
values : [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
},
]
}
]
I want to remove duplicate itemP so with a function it will look like this :
var array =
[
{
key : { id : 1 , pack : "pack 1"},
values : [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : null
},
]
}
]
When I try I always have errors. It is possible to do this?
Update
I try to do this :
console.log(array.map(pack =>
pack.values.map((item) => {
var test = JSON.stringify(item)
var set = new Set(test)
return Array.from(set).map((item)=> JSON.parse(item))
}
)
))
Unexpected end of JSON input
I also try something will filter but it doesn't work:
console.log(this.package.map(pack => pack.values.filter(
(value, index , array) => array.itemP.indexOf(value) === index
)))
Instead of mapping every key property, I suggest cloning the whole structure and setting the object value as null in the cloned one, avoiding unintentionally mutating the original structure.
function nullifyDupes(array) {
const clone = JSON.parse(JSON.stringify(array));
const seen = {};
clone.forEach(pack => {
pack.values.forEach(items => {
for (const item in items) {
const id = items[item].id;
if (seen[id]) items[item] = null;
else seen[id] = true;
}
});
});
return clone;
}
const originalArray = [{
key : { id : 1 , pack : "pack 1"},
values : [{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
}]
}];
const mutatedArray = nullifyDupes(originalArray);
console.log(mutatedArray);
To achieve expected result, use below option of using map
Loop array using map
Use nameArr to check duplicate and assigning null value
Loop values array and check the name in nameArr using indexOf and assign null
var array = [
{
key : { id : 1 , pack : "pack 1"},
values : [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
}
]
}
]
console.log(array.map(v => {
let nameArr = []
v.values = v.values.map(val => {
if(nameArr.indexOf(val.itemP.name) !== -1){
val.itemP.name = null
}else{
nameArr.push(val.itemP.name)
}
return val
})
return v
}))
You can use map and an object to check if its already exist. Like
var obj = {}
and loop over values
var values = [
{
item : { id : 1 , name : "item1"},
itemP : {id : 2 , name : "itemP12"}
},
{
item : { id : 4 , name : "item4"},
itemP : {id : 2 , name : "itemP12"}
}
]
values.map((v) => {
if(!obj[v.itemP.id + '-' + v.itemP.name]) {
obj[v.itemP.id + '-' + v.itemP.name] = true;
return v;
}
return { item : v.item }
})
You can map your array elements to array objects which don't include your duplicates using .map(). For each iteration of .map() you can again use .map() for your inner values array to convert it into an array of objects such that the duplicates are converted to null. Here I have kept a seen object which keeps track of the properties seen and their stringified values. By looping over all the properties in your object (using for...of), you can work out whether or not the key-value pair has been seen before by using the seen object.
The advantage of this approach is that it doesn't just work with one property (ie not just itemP), but it will work with any other duplicating key-value pairs.
See example below:
const array = [{key:{id:1,pack:"pack 1"},values:[{item:{id:1,name:"item1"},itemP:{id:2,name:"itemP12"}},{item:{id:4,name:"item4"},itemP:{id:2,name:"itemP12"}}]}];
const seen = {};
const res = array.map(obj => {
obj.values = obj.values.map(vobj => {
for (let p in vobj) {
vobj[p] = seen[p] === JSON.stringify(vobj[p]) ? null : vobj[p];
seen[p] = seen[p] || JSON.stringify(vobj[p]);
}
return vobj;
});
return obj;
});
console.log(res);
For an approach which just removed itemP from all object in accross your array you can use:
const array = [{key:{id:1,pack:"pack 1"},values:[{item:{id:1,name:"item1"},itemP:{id:2,name:"itemP12"}},{item:{id:4,name:"item4"},itemP:{id:2,name:"itemP12"}}]}];
let itemP = "";
const res = array.map(obj => {
obj.values = obj.values.map(vobj => {
vobj.itemP = itemP ? null : vobj.itemP;
if('itemP' in vobj) {
itemP = itemP || JSON.stringify(vobj.itemP);
}
return vobj;
});
return obj;
});
console.log(res);
im struggling a little with this, been a while since ive coded javascript ... trying to convert this
items = {
"data": [
{
"name" : "john"
},
{
"name" : "james"
},
{
"name" : "joe"
},
{
"name" : "brian"
},
{
"name" : "bojan"
},
{
"name" : "billy"
},
{
"name" : "dean"
},
{
"name" : "darren"
},
{
"name" : "doug"
}
]
}
into this format
items = {
"data": [
{
letter: "j"
names : ["john", "james", "joe"]
},
{
letter: "b"
names : ["brian", "bojan", "billy"]
},
{
letter: "j"
names : ["dean", "darren", "doug"]
},
]
}
I've been trying to do this using reduce but not having much look.... is there a simpler way to to do it?
You can use reduce to create an object with the letters as keys from which you can extrapolate the array of objects you need by iterating over the object entries using map.
const items = {"data":[{"name":"john"},{"name":"james"},{"name":"joe"},{"name":"brian"},{"name":"bojan"},{"name":"billy"},{"name":"dean"},{"name":"darren"},{"name":"doug"}]};
// `reduce` over the data to produce an object
// with letter keys, and array values where the names are added
const obj = items.data.reduce((acc, c) => {
const letter = c.name[0];
acc[letter] = (acc[letter] || []).concat(c.name);
return acc;
}, {})
// `map` over the object entries to return an array of objects
items.data = Object.entries(obj).map(([letter, names]) => {
return { letter, names }
}).sort((a, b) => a.letter > b.letter);
console.log(items);
Vanilla javascript implementation:
const items = {
"data": [
{
"name" : "john"
},
{
"name" : "james"
},
{
"name" : "joe"
},
{
"name" : "brian"
},
{
"name" : "bojan"
},
{
"name" : "billy"
},
{
"name" : "dean"
},
{
"name" : "darren"
},
{
"name" : "doug"
}
]
}
const transformed = {
data:[]
}
const findByLetter = (letter) => (element) => element.letter === letter;
for(let i = 0; i < items.data.length; i++){
const letter = items.data[i].name.split("")[0];
const elIndex = transformed.data.findIndex(findByLetter(letter));
if(elIndex > -1){
transformed.data[elIndex].names.push(items.data[i].name);
}else{
transformed.data.push({
letter,
names: [items.data[i].name],
});
}
};
console.log(transformed);
Use one reduce():
const items = {"data":[{"name":"john"},{"name":"james"},{"name":"joe"},{"name":"brian"},{"name":"bojan"},{"name":"billy"},{"name":"dean"},{"name":"darren"},{"name":"doug"}]};
let res = items.data.reduce((acc, item) => {
let l = item.name[0];
if (acc.data.filter(e => e.letter == l)[0] === undefined) acc.data.push({'letter': l, names: [] });
acc.data.filter(e => e.letter == l)[0].names.push(item.name);
return acc;
}, {"data": []})
console.log(res)