I'm trying to form the dictionary from tabs and data by iterating
I'm unable to form dictionary like structure and expected Output is mentioned
const tabs = {
first: 'first',
second: 'second',
third: 'third'
}
const data = {
accounts: {
members: [
{
node: {id: '1', name: 'first'}
},
{
node: {id: '2', name: 'second'}
},
{
node: {id: '3', name: 'third'}
},
]
}
}
let expectedOutput = {'first': '1','second':'2','third':'3'}
We have an object tabs. We can get key from this object using Object.keys(object_name). It will simply return us an array of key.
Object.keys(tabs) => [first, second,third]
data.accounts.members is also an array.We need to use array filter method to extract the node object from data.accounts.members array. Each item in array is an object. We can use object dot notation property to get value.
const filterarray = data.accounts.members.filter(it => it.node.name === tabs[item])[0]
To read first value from array just simply use filterarray[0] index.
Reduce need initial value which is an empty object.We are appending data in this object.
We can simply add data in object using object[key] = value
Here key will be tabs key. tabs is also an object we need to read the value of that key and store result in object result[tabs[item]] = filterarray.node.id
Once reduce is over we will get result.
const tabs = {
first: 'first',
second: 'second',
third: 'third'
}
const data = {
accounts: {
members: [{
node: {
id: '1',
name: 'first'
}
},
{
node: {
id: '2',
name: 'second'
}
},
{
node: {
id: '3',
name: 'third'
}
},
]
}
}
const expectedOut =
Object.keys(tabs).reduce(
(result, item) => {
const ch = data.accounts.members.filter(it => it.node.name === tabs[item])[0]
result[tabs[item]] = ch.node.id
return result
}, {})
console.log(expectedOut)
Related
I have the following two simple objects:
clinics: [
{
id: 1,
name: 'New Hampshire Veterinarian Clinic',
plans: [
'handle123',
'handle567',
]
},
{
id: 2,
name: 'Westminster Moltchester Clinic',
plans: [
'handle123',
'handle789',
]
}
],
animals: [
{
id: 1,
handle: 'handle123',
name: 'Cat',
},
{
id: 2,
handle: 'handle567',
name: 'Dog',
},
{
id: 3,
handle: 'haneld789',
name: 'Horse'
}
],
I have the following method:
updateAnimals(selectedOption, id) {
}
where selectedOption is one object from the clinics array.
I want to filter the second array so it only contains the handles mentioned in the selected option, but I'm having trouble with the arguments. I want to achieve something like this:
updateAnimals(selectedOption, id) {
let filteredAnimals = this.animals.filter(function({id, handle, name}) {
// Access the selectedOption here so I can use it to filter
});
}
But I'm not sure how to access the selected option inside the function...
Or is there a better way to do that?
You can use selectedOption just like any other variable available in a scope by simply using it directly selectedOption.something:
updateAnimals(selectedOption, id) {
let filteredAnimals = this.animals.filter({ handle } => {
return selectedOption.plans.includes(handle)
});
}
updateAnimals(selectedOption, id) {
const handles=selectedOption.plans;
let result= animals.filter(animal=>handles.includes(animal.handle));
}
i want to access the id 'qwsa221' without using array index but am only able to reach and output all of the array elements not a specific element.
i have tried using filter but couldnt figure out how to use it properly.
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Use Object.keys() to get all the keys of the object and check the values in the array elements using . notation
let lists = {
def453ed: [{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
Object.keys(lists).forEach(function(e) {
lists[e].forEach(function(x) {
if (x.id == 'qwsa221')
console.log(x)
})
})
You can use Object.Keys method to iterate through all of the keys present.
You can also use filter, if there are multiple existence of id qwsa221
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
let l = Object.keys(lists)
.map(d => lists[d]
.find(el => el.id === "qwsa221"))
console.log(l)
you can do it like this, using find
let lists = {
def453ed: [
{
id: "qwsa221",
name: "Mind"
},
{
id: "jwkh245",
name: "Space"
}
]
};
console.log(
lists.def453ed // first get the array
.find( // find return the first entry where the callback returns true
el => el.id === "qwsa221"
)
)
here's a corrected version of your filter :
let lists = {def453ed: [{id: "qwsa221",name: "Mind"},{id: "jwkh245",name: "Space"}]};
// what you've done
const badResult = lists.def453ed.filter(id => id === "qwsa221");
/*
here id is the whole object
{
id: "qwsa221",
name: "Mind"
}
*/
console.log(badResult)
// the correct way
const goodResult = lists.def453ed.filter(el => el.id === "qwsa221");
console.log(goodResult)
// filter returns an array so you need to actually get the first entry
console.log(goodResult[0])
I have a mapped an array object, now I need to get unique values from that array's children.
const arr=[
{
name: 'name1',
functions:{
0:{
name:'some1',
property: 'string'
},
1:{
name:'some1',
property: 'string'
},
2:{
name:'some3',
property: 'number'
}
}
},
]
<div>
{
arr.map((item, index) => {
let ars=[]
//console.log(item.functions)
for(const key in item.functions){
if(ars.indexOf(item.functions[key])>1){
ars.push(item.functions[key])
}
}
console.log(ars)
return <div key={index}>
<h2>{item.name}</h2>
{
ars.map((i)=>(
<p>{i.name}</p>
))
}
</div>
})
}
</div>
I need to get values like this:
some1
some3
So I need to get only one name from property string. And for number there is only one name.
You could create a Set for property. If a property hasn't been added yet, add the name for the property to the array.
const arr = [{
name: 'name1',
functions: {
0: {
name: 'some1',
property: 'string'
},
1: {
name: 'some2',
property: 'string'
},
2: {
name: 'some3',
property: 'number'
}
}
}]
const propertySet = new Set,
names = []
for (const { functions } of arr) {
Object.values(functions).forEach(o => {
if (!propertySet.has(o.property)) {
names.push(o.name);
propertySet.add(o.property)
}
})
}
console.log(names)
If uniqueness based upon the string representation of the value of property is enough and the value of name is always truthy you can use the following code:
const arr = [{name: 'name1', functions: {0: {name: 'some1', property: 'string'}, 1: {name: 'some2', property: 'string'}, 2: {name: 'some3', property: 'number'}}}];
let lookup = {};
arr.forEach(obj => {
Object.values(obj.functions).forEach(func => {
lookup[func.property] || (lookup[func.property] = func.name);
});
});
console.log(Object.values(lookup));
Note: This solution sees property: 123 and property: "123" as the same value, since the string representation is used. If the following is an option name: "", name: null, etc. then the first truthy name is used, if there is no truthy name present the last occurrence of name is used instead.
I don't know how to write the title properly, pardon me on that.
Basically I have a list of array of object that's coming from a place, I need to map them together. How how with my code below I can't make it.
const person = [
{name:'hello',id:1},
{name:'javascript',id:2},
{name:'world',id:3}
];
const selected = [2,3];
const normalized = person.map((obj,i) => obj.id === selected[i] ? Object.assign({}, obj, {checked:true}) : obj);
console.log(normalized)
https://jsfiddle.net/q9g0kazx/1/
I need to add an extra property base on the selected array. Why above code doesn't work?
If I understand you correctly, just iterate through the array using forEach and add the property if needed.
const person = [
{name: 'hello', id: 1},
{name: 'javascript',id: 2},
{name: 'world',id: 3}
];
const selected = [2,3];
person.forEach(p => {
if (selected.includes(p.id)) {
p.checked = true;
}
});
console.log(person);
Or you can use map like this:
const person = [
{name: 'hello', id: 1},
{name: 'javascript',id: 2},
{name: 'world',id: 3}
];
const selected = [2,3];
person.map(p => {
if (selected.includes(p.id)) {
p.checked = true;
}
return p;
});
console.log(person);
Notice that you have to return the object (person in our case)
You can do this:
Check if the the id in the array is present in the selected array by:
selected.includes(obj.id)
So, includes returns true if the obj.id was present in the selected array. If present(yes) then your Object.assignpart of code executes.
The reason your code was not working was because your person array and selected array don't have same number of elements(count) and perhaps not in the order as well.
So person[0] id which is 1 doesn't match with selected[0] id which 2 and so on.
const person = [{
name: 'hello',
id: 1
},
{
name: 'javascript',
id: 2
},
{
name: 'world',
id: 3
}
];
const selected = [2, 3];
const normalized = person.map((obj, i) => selected.includes(obj.id) ? Object.assign({}, obj, {
checked: true
}) : obj);
console.log(normalized);
I am trying to concat an array to an array (productsCategories) inside an array of objects.
So, here's what the productCategories array looks like:
[
{
id: 123,
items: [ { Obj1 }, { Obj2 } ]
},
{
id:456,
items: [ { Obj1 }, { Obj2 } ]
}
]
I have some new array, like [ { Obj3 }, { Obj4 } ] that I want to concat to the productCategories for the object where id = 123.
So to do this,
I've first used lodash's find to find the correct object to update and used concat to join the two arrays:
let nextItems:any = find(productCategories, { id: payload.id });
nextItems = assign({}, nextItems, { items: nextItems.items.concat(payload.items)});
So, nextItems.items has the concatenated items array.
However, I am having trouble now adding this to productCategories array. I need to find the object where id is the same as nextItems.id and then set productCategories.items equal to nextItems.items.
What is the correct way to do this?
Find the index of the object that matches the nextItems.id in the productCategories and assign the new concatenated array to it. You can use the lodash findIndex() method to find the index of the object that matches the id.
var index = _findIndex(productCategories, { id: nextItems.id });
productCategories[index].items = nextItems.items;
You can use plain JavaScript just as well. With ES6 spread syntax it can look like this:
productCategories.filter(x => x.id == payload.id)
.forEach(x => x.items.push(...payload.items));
Here is a snippet with sample data:
// Sample data
var productCategories = [{
id: 123,
items: [ { a: 1 }, { a: 2 } ]
}, {
id: 456,
items: [ { b: 1 }, { b: 2 } ]
}];
var payload = {
id: 123,
items: [ { c: 1 }, { c: 2 } ]
};
// Update with payload
productCategories.filter(x => x.id == payload.id)
.forEach(x => x.items.push(...payload.items));
// Show results
console.log(productCategories);
.as-console-wrapper { max-height: 100% !important; top: 0; }