How to Add new key and value to array in javascript? - javascript

I have two array, lets suppose have below value of array: "
var array1 = [
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing"},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi"},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}
]
and second array is :
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
Now i want to add one new key value in array1 only in those object whose value is equal to array one. In other words in want to match both array and want to add "status = true" in those that is having equal value.
new key want to add is :
{status: true}
Now my new array should be:
[
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing", status: true},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi", status: true},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}
]
Hope you understand.
Thanks in advance,

You could use forEach and find like this:
let array1=[{Id:"809cd136-02c7-4cc8-b9de-04fd3359b265",Name:"testing"},{Id:"609d3a78-8f7c-4843-acdb-2dcfc73c0d96",Name:"Delhi"},{Id:"264d54cb-b104-48ed-91db-673327ae8d0e",Name:"rohit-auditor"},{Id:"ce9691b3-dc55-4d30-baf4-7987c2b49b3e",Name:"test"},{Id:"284e9e98-8ed7-4fb7-b09f-5d1f2a668b15",Name:"aman"}],
array2=["809cd136-02c7-4cc8-b9de-04fd3359b265","609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
array2.forEach(id => {
let found = array1.find(a => a.Id === id);
if(found)
found.status = true
})
console.log(array1)
The if check is there to check if the Id in array2 exists in array1. If every Id in array2 exists in array1, you can simply change it to:
array1.find(a => a.Id === id).status = true

You can use Array#map method to iterate and create a new array and then use Array#includes method to check the value present in the array2. Where use ES6 spread syntax to combine both objects.
var newArray = array1.map(o => array2.includes(o.Id) ? {...o, ...add} : { ...add })
var array1 = [{
Id: "809cd136-02c7-4cc8-b9de-04fd3359b265",
Name: "testing"
},
{
Id: "609d3a78-8f7c-4843-acdb-2dcfc`Array#forEach`73c0d96",
Name: "Delhi"
},
{
Id: "264d54cb-b104-48ed-91db-673327ae8d0e",
Name: "rohit-auditor"
},
{
Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e",
Name: "test"
},
{
Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15",
Name: "aman"
}
]
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
var add = {
status: true
};
var newArray = array1.map(o => array2.includes(o.Id) ? {...o, ...add} : { ...add })
console.log(newArray);
If you want to update the original array then simply iterate over the array using Array#forEach method and add an additional property using Object.assign if necessary.
array1.forEach(o => array2.includes(o.Id) && Object.assign(o,add))
var array1 = [{
Id: "809cd136-02c7-4cc8-b9de-04fd3359b265",
Name: "testing"
},
{
Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96",
Name: "Delhi"
},
{
Id: "264d54cb-b104-48ed-91db-673327ae8d0e",
Name: "rohit-auditor"
},
{
Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e",
Name: "test"
},
{
Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15",
Name: "aman"
}
]
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
var add = {
status: true
};
array1.forEach(o => array2.includes(o.Id) && Object.assign(o, add))
console.log(array1);

A simple map & indexOf will be enough
var array1 = [
{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265", Name: "testing"},
{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi"},
{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},
{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},
{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}
]
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"]
var result=array1.map(el=>{
if(array2.indexOf(el.Id)>-1){
el.status=true
}
return el
})

You have to compare element of second array with id's of element of first array and add key (status) to those matching found.
var array1 = [{Id: "809cd136-02c7-4cc8-b9de-04fd3359b265",Name: "testing"},{Id: "609d3a78-8f7c-4843-acdb-2dcfc73c0d96", Name: "Delhi"},{Id: "264d54cb-b104-48ed-91db-673327ae8d0e", Name: "rohit-auditor"},{Id: "ce9691b3-dc55-4d30-baf4-7987c2b49b3e", Name: "test"},{Id: "284e9e98-8ed7-4fb7-b09f-5d1f2a668b15", Name: "aman"}];
var array2 = ["809cd136-02c7-4cc8-b9de-04fd3359b265", "609d3a78-8f7c-4843-acdb-2dcfc73c0d96"];
array2.forEach(function(secondElem) {
let matchingElemInFirstArr = array1.find(el=>el.Id==secondElem);
matchingElemInFirstArr ['status']=true;
});
console.log(array1);

Related

Extract data from array if IDs match

I am struggling to find out a solution to my problem, but at the moment I cannot come up with the right one.
When I have my two arrays of objects I want to filter based on category IDs and extract the data from the second one into a new array for example :
const array1 = [
{id: 1, name: 'Tropical'},
{id: 2, name: 'Common'}
]
const array2 = [
{id:1, name: 'Banana', category_id: 1},
{id:2, name: 'Mango', category_id: 1},
{id:3, name: 'Apple', category_id: 2},
]
And when click happens I detect the first ID and render the new array only with data that matches the ID.
Click Tropical
New array :
[
{id:1, name: 'Banana', category_id: 1},
{id:2, name: 'Mango', category_id: 1},
]
I would be happy if someone give me a hint on how can I tackle this problem. Thanks !
Correct me if I am wrong, So you need a function that received a categoryId and you need to filter out array2 based on that category_id
You can try this
const array1 = [{
id: 1,
name: 'Tropical'
},
{
id: 2,
name: 'Common'
}
]
const array2 = [{
id: 1,
name: 'Banana',
category_id: 1
},
{
id: 2,
name: 'Mango',
category_id: 1
},
{
id: 3,
name: 'Apple',
category_id: 2
},
]
function categoryFruits(categoryId) {
return array2.filter(obj => obj.id === categoryId)
}
console.log(categoryFruits(3));
Use reduce to map over each item in array1 and filter to grab the items of that category_id
const array1 = [{
id: 1,
name: 'Tropical'
},
{
id: 2,
name: 'Common'
}
]
const array2 = [{
id: 1,
name: 'Banana',
category_id: 1
},
{
id: 2,
name: 'Mango',
category_id: 1
},
{
id: 3,
name: 'Apple',
category_id: 2
},
]
const obj = array1.reduce((acc, cur) => {
acc[cur.name] = array2.filter(v => v.category_id === cur.id)
return acc
}, {})
console.log(obj)
You could do something like filtering array2 and taking all the elements that have Tropical as name in array1.
const array1 = [
{id: 1, name: 'Tropical'},
{id: 2, name: 'Common'}
]
const array2 = [
{id:1, name: 'Banana', category_id: 1},
{id:2, name: 'Mango', category_id: 1},
{id:3, name: 'Apple', category_id: 2},
]
// take tropical friuts
let tropicalFriuts = array2.filter(x => x.category_id === array1.filter(y => y.name === 'Tropical')[0].id);
console.log(tropicalFriuts);
If I understood your problem you want before find the id, based on the name of the category, and later filter array2 data based on this id.
const array1 = [{
id: 1,
name: 'Tropical'
},
{
id: 2,
name: 'Common'
}
]
const array2 = [{
id: 1,
name: 'Banana',
category_id: 1
},
{
id: 2,
name: 'Mango',
category_id: 1
},
{
id: 3,
name: 'Apple',
category_id: 2
},
]
const id_key = array1.find(item=>item.name === 'Tropical').id;
const result = array2.filter(item=>item.category_id === id_key);
console.log(result);

JavaScript: add new property to array elements according to another array

I have two arrays.
When comparing, if arr1 property id matches with arr2 property id, then add new property tag: assign else add tag: ''
I have tried the below code:
var result = arr1.filter(({ id: id }) =>
!arr2.some(({ name: name }) => name === id)
);
Sample inputs:
var arr1 = [
{id:1, name: "ram"},
{id:24, name: "zen"},
{id: 3, name: "sam"}
]
var arr2 = [
{id:24, name: "zen"},
{id: 3, name: "sam"}
]
Expected Output:
[
{id:1, name: "ram", tag:''},
{id:24, name: "zen", tag: 'yes'},
{id: 3, name: "sam", tag: 'yes'}
]
Create a Set of ids in arr2 using Array#map
Again, using Array#map, iterate over arr1 and set tag using Set#has
const
arr1 = [ {id:1, name: "ram"}, {id:24, name: "zen"}, {id: 3, name: "sam"} ],
arr2 = [ {id:24, name: "zen"}, {id: 3, name: "sam"} ];
const arr2IdsSet = new Set( arr2.map(({ id }) => id) );
const res = arr1.map(e => ({ ...e, tag: arr2IdsSet.has(e.id) ? 'yes' : '' }));
console.log(res);

Get specific value from array object in a single line in typescript

I have a following array
const _array = [{id: 1, name: 'Adam'}, {id:3, name: 'Crystal'}, {id:2, name: 'Bob'}, {id: 4, name: 'Daisy'}];
How to write a single line of code in typescript to get item where name equal to Crystal from the array?
You can use array find method like following:
const _array = [
{ id: 1, name: "Adam" },
{ id: 3, name: "Crystal" },
{ id: 2, name: "Bob" },
{ id: 4, name: "Daisy" },
];
const item = _array.find((item) => item.name === "Crystal");
console.log(item);
Output
{ id: 3, name: 'Crystal' }

Search/Filter nested Array Javascript/Lodash

For my React.js project I would like to create a search-filter of a nested Array. Users will search with an input-field.
var dataExample = [
{
type: "human", details: [
{id: 1, name: "Peter", description: "friendly, black-hair"},
{id: 5, name: "Susan", description: "blond"}
]
},
{
type: "animal", details: [
{id: 2, name: "Will", description: "lazy, cute"},
{id: 3, name: "Bonny", description: "beautiful"}
]
}
];
In my search-input-field I want to look for "name" or something in "description". The data structure of the array should remain the same.
The output when I'm searching for "friendly" or "Peter" should be:
[
{
type: "human", details: [
{id: 1, name: "Peter", description: "friendly, black-hair"}
]
}
];
Now I tried something like this:
let myfilter = dataExample.filter((data) => {
data.details.filter((items) => {
return (items.type.indexOf("human") !== -1 || //input of user
items.description.indexOf("friendly"))
})
})
Unfortunately, this is not how it works. Can anybody help me? Lodash would be no problem, too. Thank you so much.
You can use array#reduce with array#filter and to check for your word you can use string#incldues.
const dataExample = [ { type: "human", details: [ {id: 1, name: "Peter", description: "friendly, black-hair"}, {id: 5, name: "Susan", description: "blond"} ] }, { type: "animal",details: [ {id: 2, name: "Will", description: "lazy, cute"}, {id: 3, name: "Bonny", description: "beautiful"} ] } ],
term = 'Peter',
result = dataExample.reduce((r, {type,details}) => {
let o = details.filter(({name,description}) => name.includes(term) || description.includes(term));
if(o && o.length)
r.push({type, details : [...o]});
return r;
},[]);
console.log(result);
Here are some examples without lodash.
var dataAll = [
{
type: "human",
details: [
{id: 1, name: "Peter", description: "friendly, black-hair"},
{id: 5, name: "Susan", description: "blond"}
]
},
{
type: "animal",
details: [
{id: 2, name: "Will", description: "lazy, cute"},
{id: 3, name: "Bonny", description: "beautiful"}
]
}
];
var entryTypeFilter = data => data.type.indexOf("hum") !== -1;
var entryDetailDescFilter = data => data.description.indexOf("friend") !== -1;
var entryDetailsMapper = data => {
return {
type: data.type,
details: data.details.filter(entryDetailDescFilter)
};
};
var entryNoDetailsFilter = data => data.details && data.details.length !== 0;
var dataFilteredByType = dataAll.filter(entryTypeFilter);
var dataFilteredByDesc = dataAll.map(entryDetailsMapper);
var dataFilteredByTypeAndDesc = dataAll.filter(entryTypeFilter).map(entryDetailsMapper);
var dataFilteredByDescTrimmingEmptyDetailEntries = dataAll.map(entryDetailsMapper).filter(entryNoDetailsFilter);
In modern javascript you might want to search on how to use the ... keyword for the mapping callback functions.

Categorize Similar items into separate objects from Array lists

I have an array of items that I get from API as a response body.
data = [{id: 1, category: "kitchen", name: "noodles"},
{id: 2, category: "general", name: "Wi-Fi"},
{id: 3, category: "sports", name: "Football"},]
I want to iterate over the arrays, and get the data like :
var categorized = {
kitchen: [{id: 1, category: "kitchen", name: "noodles"}],
general : [{id: 2, category: "general", name: "Wi-Fi"}],
sports : [{id: 3, category: "sports", name: "Football"}]
};
Is there any lodash methods, or any ES6 shortcuts for this ?
In answer to your question 'is there a lodash method?' Yes: https://lodash.com/docs/4.17.4#groupBy. For your specific example:
const categorized = _.groupBy(data, 'category');
Edit: You could roll your own groupBy type function with ES6 as in another example. But if you are using lodash anyway this is a whole lot cleaner.
I used array.reduce to get the structure
var data = [{
id: 1,
category: "kitchen",
name: "noodles"
}, {
id: 2,
category: "general",
name: "Wi-Fi"
}, {
id: 3,
category: "sports",
name: "Football"
}]
var newData = data.reduce(function(obj, v, i) {
obj[v.category] = obj[v.category] || [];
obj[v.category].push(v);
return obj;
}, {});
console.log(newData);
In ES6 you could so using:
var newData = data.reduce((obj, v, i)=> {
obj[v.category] = obj[v.category] || [];
obj[v.category].push(v);
return obj;
}, {});
console.log(newData);

Categories