Replacing two property values in array object and creating new array - javascript

***EDIT I should have been provided a more clear question and provided better data.
I need to take an existing array of objects, replace the names depending on two different id's, and create a new array out of them.
My JSON:
const legendData = [{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 1,
{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 2,
},
{
"assetManagerId": 8,
"name": "Barings",
"fileTypeId": 2,
},
{
"assetManagerId": 5,
"name": "BlackRock",
"fileTypeId": 1,
}]
I need the AIM Derivatives names to change to the below, however, keep the rest the same.
const = legendData[{
"assetManagerId": 11,
"name": "AIM Derivatives ODIN",
"fileTypeId": 1,
{
"assetManagerId": 11,
"name": "AIM Derivatives CMF",
"fileTypeId": 2,
},
{
"assetManagerId": 8,
"name": "Barings",
"fileTypeId": 2,
},
{
"assetManagerId": 5,
"name": "BlackRock",
"fileTypeId": 1,
}]
I got halfway with my code below, however, don't know how to combine both. The below only changes if the fileTypeId is 1 but not 2.
const newArr = legendData.map(item => item.assetManagerId === 11 && item.fileTypeId === 1? {
...item, name: "AIM Derivatives ODIN"
} : item)
console.log(newArr)

You can create a dictionary and store the fileTypeId and relevant text
const legendData = [{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 1,
},
{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 2,
}
]
const idMap = {
1: "AIM Derivatives ODIN",
2: "AIM Derivatives CMF"
}
// check if the assetManagerId matches and if the `fileTypeId` is one of the key in dictionary
const newArr = legendData.map(item => item.assetManagerId === 11 && idMap[item.fileTypeId] ? {
...item,
// if one of the key the get the relevant value of that key
name: idMap[item.fileTypeId]
} : item)
console.log(newArr)

You could to try with a json config that keys are assetManagerId and fileTypeId and values are the new name.
const newNamesConfig = {
11: {
1: { name: 'AIM Derivatives ODIN' },
2: { name: 'AIM Derivatives CMF' },
},
}
const derivatesNames = [{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 1,
},
{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 2,
}];
const renamedArray = derivatesNames.map(derivate => Object.assign({}, derivate,newNamesConfig[derivate.assetManagerId][derivate.fileTypeId]));
console.log(renamedArray)

You can use map. While you will map, you can get desired name by fileTypeId from object which contains desired name:
let arr = [{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 1,
},
{
"assetManagerId": 11,
"name": "AIM Derivatives",
"fileTypeId": 2,
}]
const names = {1: 'AIM Derivatives ODIN', 2:'AIM Derivatives CMF'}
const result = arr.map(({name, fileTypeId, ...rest}) =>
({name: names[fileTypeId], fileTypeId, ...rest}))
console.log(result)
UPDATE:
let arr = [{ "assetManagerId": 11, "name": "AIM Derivatives", "fileTypeId": 1},{
"assetManagerId": 11, "name": "AIM Derivatives", "fileTypeId": 2,
},
{
"assetManagerId": 8, "name": "Barings", "fileTypeId": 2,
},
{
"assetManagerId": 5, "name": "BlackRock", "fileTypeId": 1,
}]
const names = {'AIM Derivatives': { 1: 'AIM Derivatives ODIN', 2:'AIM Derivatives CMF'}}
const result = arr.map(({name, fileTypeId, ...rest}) =>
({
name: names[name] ? names[name][fileTypeId] : name,
fileTypeId,
...rest
}))
console.log(result)

Related

copying an array of object and ordering some items

I have an array of object and I want to copy that array of object to another array while modifying some items, like copying id only by ascending order and copying only the value of trophies of basketball to trophies. How to do it?
const item = [{
"id": 33,
"name": "John"
"trophies": {
"basketball" : 2,
"baseball" : 5
},
"profile": "profile/212"
}
{
"id": 12,
"name": "Michael"
"trophies": {
"basketball" : 6,
"baseball" : 7
},
"profile": "profile/341"
}
]
I want the above array of object after copying to look something like
const item2 = [{
"id": 12,
"name": "Michael"
"trophies": 6,
"profile": "http://collegeprofile.com/profile/341"
},
{
"id": 33,
"name": "John"
"trophies": 2,
"profile": "http://collegeprofile.com/profile/212"
}
]
You can sort by id ascending order using Array.prototype.sort
And map basketball value to trophies using Array.prototype.map.
const item = [{
"id": 33,
"name": "John",
"trophies": {
"basketball": 2,
"baseball": 5
},
"profile": "profile/212"
}, {
"id": 12,
"name": "Michael",
"trophies": {
"basketball": 6,
"baseball": 7
},
"profile": "profile/341"
}];
const output = item.sort((a, b) => (a.id - b.id)).map((item) => ({
...item,
trophies: item.trophies.basketball,
profile: "http://collegeprofile.com/" + item.profile
}));
console.log(output);

Compare two different arrays and save matched record in another array in Java Script [duplicate]

This question already has answers here:
How to filter an array in javascript?
(9 answers)
Closed 2 years ago.
I need to compare two arrays and when records match then save mached record to another array
Array1 =
[ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ]
Array2 =
[ "[PACKNAME]", "[BALANCE]" ]
Matched Record Saved Array
[ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 12, "value": "[BALANCE]" } ]
How can I achive this approch using javascript.
I could do matching and save array for same kind of arrays using below code but I'm unable to do above scenario.
let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let map = {};
firstArray.forEach(i => map[i] = false);
secondArray.forEach(i => map[i] === false && (map[i] = true));
let jsonArray = Object.keys(map).map(k => ({ name: k, matched: map[k] }))
This is a simple filter usecase:
let array1 = [ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ];
let array2 = [ "[PACKNAME]", "[BALANCE]" ];
let array3 = array1.filter((el) => array2.includes(el.value));
console.log(array3);
More about Array.prototype.filter()
If I understand correctly what you are trying to do: you can just filter the first array for elements whose value exists in the second array, as follows:
const firstArray = [
{ "phId": 10, "value": "[PACKNAME]" },
{ "phId": 11, "value": "[PACKTYPE]" },
{ "phId": 12, "value": "[BALANCE]" },
{ "phId": 17, "value": "[DURATION]" }
]
const secondArray = [ "[PACKNAME]", "[BALANCE]" ]
const matchedArray = firstArray.filter(({ value }) => secondArray.includes(value))
Use filter
const arr_one = [ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ]
const arr_two = [ "[PACKNAME]", "[BALANCE]" ]
const matched = arr_one.filter( ( item ) => arr_two.includes( item.value ) )
console.log(matched)
/*
Matched Record Saved Array
[ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 12, "value": "[BALANCE]" } ]
*/
array1=[ { "phId": 10, "value": "[PACKNAME]" }, { "phId": 11, "value": "[PACKTYPE]" }, { "phId": 12, "value": "[BALANCE]" }, { "phId": 17, "value": "[DURATION]" } ]
array2=[ "[PACKNAME]", "[BALANCE]" ]
res = array1.filter(o => array2.includes(o.value))
console.log(res)
You don't want all items = you don't want map.
You want some items that match a condition = you want filter.
try this:
var Array1 = [
{"phId": 10, "value": "[PACKNAME]"},
{"phId": 11, "value": "[PACKTYPE]"},
{"phId": 12, "value": "[BALANCE]"},
{"phId": 17, "value": "[DURATION]"}
];
var Array2 = ["[PACKNAME]", "[BALANCE]"];
var MatchedRecordSavedArray = Array1.filter(item => Array2.includes(item.value));
console.log(MatchedRecordSavedArray);

Filtering an array based on multiple arrays inputs

I have three arrays.
1. Existing viewers array - existingViewers
New viewers array - newViewers
Permitted Viewers array - permittedViewers
permittedViewers is used for rendering the drop-down. And I wish to filter the newViewers and existingViewers entries from the permittedViewers.
I am doing this as three steps. And I am afraid this is not the optimized way. Can someone suggest the ideal way of doing this?
The expected result is
[
{
"id": 4,
"name": "name4"
},
{
"id": 5,
"name": "name5"
},
{
"id": 6,
"name": "name6"
}
]
let existingViewers = [{
"viewerId": 1,
"name": "name1"
},
{
"viewerId": 2,
"name": "name2"
}
],
newViewers = [
{
"viewerId": 3,
"name": "name3"
}
],
permittedViewers = [{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
},
{
"id": 3,
"name": "name3"
},
{
"id": 4,
"name": "name4"
},
{
"id": 5,
"name": "name5"
},
{
"id": 6,
"name": "name6"
}
]
let grouped = [...existingViewers, ...newViewers]
let viewerFilter = grouped.map(viewer => { return viewer.viewerId; });
let filteredPermittedViewers = permittedViewers.filter(viewer => !viewerFilter.includes(viewer.id));
console.log(filteredPermittedViewers)
I'd make a Set of the ids of the first two arrays, and then filter the third by whether the set includes the id. (Sets have O(1) lookup time)
let existingViewers=[{"viewerId":1,"name":"name1"},{"viewerId":2,"name":"name2"}],newViewers=[{"viewerId":3,"name":"name3"}],permittedViewers=[{"id":1,"name":"name1"},{"id":2,"name":"name2"},{"id":3,"name":"name3"},{"id":4,"name":"name4"},{"id":5,"name":"name5"},{"id":6,"name":"name6"}];
const ids = new Set([...existingViewers, ...newViewers].map(({ viewerId }) => viewerId));
const output = permittedViewers.filter(({ id }) => !ids.has(id));
console.log(output);
You can compress all three statements into a single statement -- just replace the variable name with the statement that creates it:
let existingViewers = [{
"viewerId": 1,
"name": "name1"
},
{
"viewerId": 2,
"name": "name2"
}
],
newViewers = [
{
"viewerId": 3,
"name": "name3"
}
],
permittedViewers = [{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
},
{
"id": 3,
"name": "name3"
},
{
"id": 4,
"name": "name4"
},
{
"id": 5,
"name": "name5"
},
{
"id": 6,
"name": "name6"
}
]
let filteredPermittedViewers = permittedViewers.filter(viewer => ! [...existingViewers, ...newViewers].map(viewer => viewer.viewerId).includes(viewer.id));
console.log(filteredPermittedViewers)

Function that returns all the elements where field is 1

I have the array:
var tabs = [
{"id": 1, "Name": "Top", "Paris": 1, "London": 1, "Rome": 1},
{"id": 2, "Name": "Best", "Paris": 1, "London": 0, "Rome": 0},
{"id": 3, "Name": "Cheap", "Paris": 0, "London": 1, "Rome": 0}
];
How can I write a function that receives as argument one of the towns (London or Paris or Rome) different each time and returns the elements of the array which the argument is 1? For example, I want to take all the elements where London=1.
var tabs= [
{ "id": 1, "Name": "Top","Paris":1,"London":1, "Rome":1},
{ "id": 2, "Name": "Best","Paris":1,"London":0,"Rome":0},
{ "id": 3, "Name": "Cheap","Paris":0,"London":1,"Rome":0}
];
var getElementsWith=function(array,name){
var myElements=[];
array.forEach(function(tab){
if(tab[name]===1)
myElements.push(tab);
});
return myElements;
};
console.log(getElementsWith(tabs,"Paris"));
You can use Array.filter:
function filterList(cityName) {
return tabs.filter(function(o) {
return o[cityName] === 1;
});
}
You could use a generic function, which takes the array, key and value, you are looking for. Then use Array#filter for the sub set.
function filter(array, key, value) {
return array.filter(function (object) {
return object[key] === value;
});
}
var tabs = [{ "id": 1, "Name": "Top","Paris":1,"London":1, "Rome":1 },{ "id": 2, "Name": "Best","Paris":1,"London":0,"Rome":0 },{ "id": 3, "Name": "Cheap","Paris":0,"London":1,"Rome":0 }],
result = filter(tabs, 'London', 1);
console.log(result);

lodash merge and combine objects

I have an array of objects as below that I read from my database using sequelize ORM:
I want to have all my videos from a section, but the better I can return using sequelize is :
[{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": {
"id": 11,
"source": "sourrrccrsss22222",
"videoSubSection": 2
}
},
{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": {
"id": 12,
"source": "sourrrccrsss111",
"videoSubSection": 2
}
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": {
"id": 13,
"source": "sourrrcc",
"videoSubSection": 1
}
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": {
"id": 14,
"source": "sourrrcc",
"videoSubSection": 1
}
}]
Is there a way to merge and combine the objects in my array to obtain something like this :
[{
"id": 2,
"name": "Ru",
"subsection": 1,
"Video": [{
"id": 11,
"source": "sourrrccrsss22222",
"videoSubSection": 2
},{
"id": 12,
"source": "sourrrccrsss111",
"videoSubSection": 2
}]
},
{
"id": 1,
"name": "Oc",
"subsection": 1,
"Video": [{
"id": 13,
"source": "sourrrcc",
"videoSubSection": 1
},{
"id": 14,
"source": "sourrrcc",
"videoSubSection": 1
}]
}
The function that approach the most is _.mergeWith(object, sources, customizer) but the main problem I have is that I have on object and need to merge this object.
In plain Javascript, you can use Array#forEach() with a temporary object for the arrays.
var data = [{ id: 2, name: "Ru", subsection: 1, Video: { id: 11, source: "sourrrccrsss22222", VideoSubSection: 2 } }, { id: 2, name: "Ru", subsection: 1, Video: { id: 12, source: "sourrrccrsss111", VideoSubSection: 2 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 13, source: "sourrrcc", VideoSubSection: 1 } }, { id: 1, name: "Oc", subsection: 1, Video: { id: 14, source: "sourrrcc", VideoSubSection: 1 } }],
merged = function (data) {
var r = [], o = {};
data.forEach(function (a) {
if (!(a.id in o)) {
o[a.id] = [];
r.push({ id: a.id, name: a.name, subsection: a.subsection, Video: o[a.id] });
}
o[a.id].push(a.Video);
});
return r;
}(data);
document.write('<pre>' + JSON.stringify(merged, 0, 4) + '</pre>');
Maybe try transform():
_.transform(data, (result, item) => {
let found;
if ((found = _.find(result, { id: item.id }))) {
found.Video.push(item.Video);
} else {
result.push(_.defaults({ Video: [ item.Video ] }, item));
}
}, []);
Using reduce() would work here as well, but transform() is less verbose.
You can do it this way (test is your db output here)
var result = [];
var map = [];
_.forEach(test, (o) => {
var temp = _.clone(o);
delete o.Video;
if (!_.some(map, o)) {
result.push(_.extend(o, {Video: [temp.Video]}));
map.push(o);
} else {
var index = _.findIndex(map, o);
result[index].Video.push(temp.Video);
}
});
console.log(result); // outputs what you want.

Categories

Resources