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.
Related
What I am trying to achieve is:
Find if the text object within array is empty.
If criteria from no1 is matched, then return id value that sits in the top level of that object.
https://codesandbox.io/s/cranky-swirles-gb6ct?file=/src/App.js:410-412
In the code sandbox's example I have added two objects, with empty text strings and in that case I would expect to get an array of strings back (result = ['662e4120', '782h7a9x'])
I am able to find empty values, however I am not sure how to return object from the upper scope.
If you can't access the codeSandbox, snippet is attached just below:
const array = [
{
id: "5548d3c2",
state: {
properties: [
{
text: "text",
key: "fs5a"
}
]
}
},
{
id: "662e4120",
state: {
properties: [
{
text: "",
key: "m03n"
}
]
}
},
{
id: "782h7a9x",
state: {
properties: [
{
text: "",
key: "y5x1"
}
]
}
}];
const findItem = () => {
return array
.map((item) => item.state)
.map((item) => item.properties)
.flat()
.filter((item) => item.text === "");
};
Try to do something like this https://codesandbox.io/s/jovial-mcnulty-2fwh4
export default function App() {
const array = [
{
id: "5548d3c2",
state: {
properties: [
{
text: "text",
key: "fs5a"
}
]
}
},
{
id: "662e4120",
state: {
properties: [
{
text: "",
key: "m03n"
}
]
}
},
{
id: "782h7a9x",
state: {
properties: [
{
text: "",
key: "y5x1"
}
]
}
}
];
const findItem = () => {
return array.filter(obj=>obj.state.properties[0].text==="").map(obj=>obj.id)
};
console.log(findItem());
return <div className="App"></div>;
}
Here, we are filtering on the original array based on a predicate which is obj=>obj.state.properties[0].text==="". This basically get all the elements of the array which satisfy this predicate function. After this we are just applying map over the result to get the ids of the array elements satisfying this predicate function.
To get an array with the ids of the objects with no text you have to change the order or your iterations.
.filter() the array for the elements with empty text fields.
.map() the remaining elements to the values you are aiming for
When mapping or filtering you can't just go one but as many levels deep as you like. Since 'properties' holds an array and you want the first element, you can access that with the index array[0] (with that the flat() you did is superfluous)
const findItem = () => {
return array
.filter(item => item.state.properties[0].text === "") // (2) [{…}, {…}] the original items with no text
.map(item => item.id) // ['662e4120', '782h7a9x']
};
(code might be as well embedded as a snippet, which can be run directly)
const array = [
{
id: "5548d3c2",
state: {
properties: [
{
text: "text",
key: "fs5a"
}
]
}
},
{
id: "662e4120",
state: {
properties: [
{
text: "",
key: "m03n"
}
]
}
},
{
id: "782h7a9x",
state: {
properties: [
{
text: "",
key: "y5x1"
}
]
}
}];
const findItem = () => {
return array
.filter(item => item.state.properties[0].text === "") // (2) [{…}, {…}] the original items with no text
.map(item => item.id) // ['662e4120', '782h7a9x']
};
console.log(findItem())
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)
I am trying to use .map() and ES6 syntax to return a truncated version of each object in my array. I can do this to get one value from the original object passed on:
return dbJobs.map(job =>
job.data.modType
);
But how would I use ES6 syntax to handle taking an array of objects where each object looks like this:
{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}
... and return an array of objects where each object has two properties from the original objects, like this:
{
name: "name value",
modType: "report"
}
You could use a destructuring and map objects with short hand properties.
var dbJobs = [{ id: 123, name: "name value", data: { modType: "report", category: "value" } }],
result = dbJobs.map(({ name, data: { modType } }) => ({ name, modType }));
console.log(result);
So with Array.prototype.map() you can create a new structure based on its function's return value.
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
Think about the following:
const array = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
const result = array.map(e => {
return {
name: e.name,
modeType: e.data.modType
}
});
console.log(result);
Or the same with destructuring:
const array = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
const result = array.map(({name, data: {modType}}) => {
return {
name,
modType
}
});
console.log(result);
I hope that helps!
I believe this will do what you need:
let obj = [{
id: 123,
name: "name value",
data: {
modType: "report",
category: "value"
}
}];
let res = obj.map(item => {
return {
modType: item.data.modType,
category: item.data.category
}
});
console.log(res);
You can try this simple js code
arr = arr.map(item => {
const ob = {} // create temporary object
ob.name = item.name; // asign props from array object
ob.modType = item.data.modType; // asign props from array object
return ob // just return create object
})
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 object:
var roles = { roles: [0: { name: 'admin' }, 1: { name: 'user' }] }
How I can check if value user exists?
I tried do:
console.log(('user' in roles));
But this return false. Why?
With a proper object, you could treat roles.roles as array and find the value with Array#some.
This works for any array like structure with an assignment to an array with Object.assign.
function check(name) {
return Object.assign([], roles.roles).some(o => o.name === name);
}
var roles = { roles: { 0: { name: 'admin' }, 1: { name: 'user' } } };
console.log(check('user'));
console.log(check('bar'));
By taking an array directly, you coult omit the assignment part.
function check(name) {
return roles.roles.some(o => o.name === name);
}
var roles = { roles: [{ name: 'admin' }, { name: 'user' }] };
console.log(check('user'));
console.log(check('bar'));
in operator checks for property not for it's values
let test = {'a':1,'b':2}
console.log('a' in test)
console.log(1 in test)
How can i search values
Here using some method of array i am checking whether desired value is in object or not.
var roles = { roles: [{ name: 'admin' },{ name: 'user' }] }
let searchValue = (input,searchKey) => {
return input.some(( {name} ) => name === searchKey) //
}
console.log(searchValue(roles.roles, 'user'))
console.log(searchValue(roles.roles, 'user not foound'))