Regarding Object in JavaScript - javascript

How to loop through an array of object got similar key and different value for Example if,
arrayOfObjects = [
{ parent: 'relatedParty', child: 'role === CEO', andOr = '&&' }
{ parent: 'relatedParty', child: 'name === Arun' , andOr = '||'}
{ parent: 'relatedParty', child: ' id === 123', andOr = '&&' }
{ parent: 'cusotm', child: 'contact === DAP', andOr = '||' }
{ parent: 'custom', child: 'team==dap', andOr = '&&' }
{ parent: 'multiple', child: 'key ===keys', andOr = '||' }
{ parent: 'multiple', child: 'value=== values', andOr = '&&' }
].
im stuck in a position where how can i iterate through this and get output like if
first object of parent is === second object, then I want them to add into an array and finally those values should be inside another array
[[role === CEO && name === Arun && id === 123 &&], [contact === DAP || team==dap && ],[ key ===keys || value=== values &&]]

Your example is not a valid array, are you getting it from somewhere else, like a http request?
Anyway, after fixing it to a valid array, you can try grouping by parent, and them mapping the values into what you need.
Grouping could be like:
const grouped = {}
arrayOfObjects.forEach(obj => {
if (!grouped[obj.parent]) {
grouped[obj.parent] = []
}
grouped[obj.parent].push(obj)
})
You can also use reduce, or other ways to group by parent.
After it, just map the values into what you want:
const result = Object.values(grouped).map(group => {
return group.map(obj => `${obj.child} ${obj.andOr}`).join(' ')
})
If you need it in string format to send to some api, do it like:
const body = JSON.stringify(result)

Here is a more concise way to handle your problem:
const arrayOfString = arrayOfObjects.reduce((acc, {parent, child, andOr}) => {
const value = `${child} ${andOr}`
acc[parent] = acc[parent] ? [`${acc[parent] || ''} ${value}`] : [`${value}`]
return acc
}, {})
const result = Array.from(Object.values(arrayOfString))

Related

i wanna return correctly children's object. how can i?

function Ha8(arr, id) {
let result = [];
for(let i = 0; i < arr.length; i++) {
if(Array.isArray(arr[i].children)) {
// if it is a array, it going to be run recursive
result.push(arr[i].children)
const col = Ha8(result[i], id);
if(col === id) {
// find it in array in array
return result
// then return the id object,
} else {
continue; // still can't find.. go ahead!
}
} else if (arr[i]['id']===id) {
return arr[i] // will return valid id object
}
return null // if its none , return null, or parameter id is undefined.
}
}
I m write Intended direction. but its not work..
how can i fix ? give me some tip please.
let input = [
{
id: 1,
name: 'johnny',
},
{
id: 2,
name: 'ingi',
children: [
{
id: 3,
name: 'johnson',
},
{
id: 5,
name: 'steve',
children: [
{
id: 6,
name: 'lisa',
},
],
},
{
id: 11,
},
],
},
{
id: '13',
},
];
output = Ha8(input, 5);
console.log(output); // --> { id: 5, name: 'steve', children: [{ id: 6, name: 'lisa' }] }
output = Ha8(input, 99);
console.log(output); // --> null
I wanna return like that, but only return 'null' ..
need to check children's id and return children's object by using recursive.
so i write like that. but i have no idea..
how to return correctly children id's element?
I will give you an answer using a totally different approach, and using the magic of the JSON.stringify() method, more specifically the replacer optional parameter, which allows the use of a callback function that can be used as a filter.
As you can see, it simplifies a lot the final code. It could also be modified to introduce not only an id, but also any key or value, as I did in my final approach.
EDIT: Following your suggestion, as you prefer your function to be recursive, I recommend you to use the Array.reduce() method. It allows an elegant iteration through all the properties until the needs are met.
Using null as initial value, which is the last argument of the reduce method, it allows to iterate through all fields in the array in the following way:
The first if will always be skipped on the first iteration, as the initial value is null.
The second if will set the currentValue to the accumulator if the property id exists and is equal to the value you are trying to find
The third if, which you could add an Array.isArray() to add a type validation, will check if the property children exists. As it is the last one, it will only work if all the other conditions aren't met. If this property exists, it will call again Ha8Recursive in order to start again the process.
Finally, if neither of this works, it should return null. The absence of this last condition would return undefined if the input id doesn't exist
const Ha8 = (array, inputKey, inputValue) => {
let children = null;
JSON.stringify(array, (key, value) => {
if (value[inputKey] && value[inputKey] === inputValue) {
children = value;
}
return value;
});
return children;
};
const Ha8Recursive = (array, inputKey, inputValue) => {
return array.reduce((accumulator, currentValue) => {
if (accumulator) {
return accumulator;
} else if (currentValue[inputKey] && currentValue[inputKey] === inputValue) {
return currentValue;
} else if (currentValue.children) {
return Ha8Recursive(currentValue.children, inputKey, inputValue);
} else {
return null;
}
}, null)
}
const input = [{"id":1,"name":"johnny"},{"id":2,"name":"ingi","children":[{"id":3,"name":"johnson"},{"id":5,"name":"steve","children":[{"id":6,"name":"lisa"}]},{"id":11}]},{"id":"13"}];
console.log('JSON stringify function');
console.log(Ha8(input, 'id', 5));
console.log('Recursive function')
console.log(Ha8Recursive(input, 'id', 5));

How to use spread operator to delete an object from array of objects using spread operator using react?

i want to delete an object from array of objects using spread operator.
i have an array of objects like below,
const list= [
{
id: '1',
name: 'first_item',
},
{
id: '2',
name: 'second_item',
},
]
i can add another object say "next_item" like below
const next_item = {
id: '3',
name: 'next',
}
const final = [...list, next_item]
similary how can i delete delete_item from list
const delete_item = {
id: '2',
name: 'second_item',
},
Could someone help me with this. thanks.
There is no such thing with spread operator, but if you still want to force, here you go
var arrayObj = [1,2,3,4,5,6]
const index = arrayObj.findIndex(elm => elm === 5)
const removed = [...arrayObj.slice(0,index) ,
...arrayObj.slice(index+1,arrayObj.length)]
console.log(removed)
But there is no benefit of using it like this
You can use some of the destructuring features like this :
var arrayObj = [1,2,3,4,5,6,7];
var [first , second , ...rest ] = arrayObj;
console.log(first , second , rest);
You can use filter
list = list.filter(item => {
return item.id !=2;
})
Or can use a function like the below
const removeFromList = (list, itemId) => {
return list.filter(item => {
return item.id != itemId;
});
}

Cannot access value of object property

I am looping though an object to retrieve some properties but for some reason I cannot access the value of a nested object property.
This is my looping function:
parseContacts = (contacts) => {
return contacts.map(contact => {
let parsedContact = {};
Object.keys(contact).forEach(key => {
if (key === 'givenName') {
parsedContact.firstName = contact[key];
} if (key === 'familyName') {
parsedContact.surname = contact[key];
} if (key === 'phoneNumbers') {
parsedContact.phoneNumber = contact[key][0].number;
}
})
return parsedContact;
})
}
firstName and surname work fine, but in the last if statement I get undefined. the property with key phoneNumbers it is an array of objects, and this is item 0 in the array:
{id: "302", label: "mobile", number: "+44 7X7X 50XX72"}
When I use this code instead:
} if (key === 'phoneNumbers') {
parsedContact.phoneNumber = contact[key][0];
}
without .number on the end I get the whole object back fine, I just can't get back only the number property from the object.
Update
On closer inspection, the array which has over 800 large objects in, some of the lengths of the phoneNumbers arrays were 0 so the property did not exist. This was causing the whole function to fail. Thanks for the comments below.
My solution was to add to the if statement:
if (key === 'phoneNumbers' && contact[key].length)
You can prevent the empty phoneNumbers array issue like this:
contact[key] && contact[key].length ? contact[key][0].number : ''
const parseContacts = contacts => {
return contacts.map(contact => {
let parsedContact = {}
Object.keys(contact).forEach(key => {
switch (key) {
case 'givenName':
parsedContact.firstName = contact[key]
break
case 'familyName':
parsedContact.surname = contact[key]
break
case 'phoneNumbers':
parsedContact.phoneNumber = contact[key] && contact[key].length ? contact[key][0].number : ''
}
})
return parsedContact
})
}
const contacts = []
for (let i = 0; i < 10; i++) {
contacts.push({
givenName: faker.name.firstName(),
familyName: faker.name.lastName(),
phoneNumbers: [
{
id: faker.random.uuid(),
label: 'mobile',
number: faker.phone.phoneNumber()
}, {
id: faker.random.uuid(),
label: 'mobile',
number: faker.phone.phoneNumber()
}
]
})
}
contacts.push({
givenName: faker.name.firstName(),
familyName: faker.name.lastName(),
phoneNumbers: []
})
contacts.push({
givenName: faker.name.firstName(),
familyName: faker.name.lastName(),
phoneNumbers: null
})
console.log('RESULT ' + JSON.stringify(parseContacts(contacts)))
<script src="https://rawgit.com/Marak/faker.js/master/examples/browser/js/faker.js"></script>

How to check if key value pair in a array of objects in empty using react or javascript?

Hi i have the data like below,
data = [
{
attributes: [{key: '', value: ''}, {key: 'name1', value: ''}],
info: '',
meshes: [],
}
{
attributes: [{key: '', value: ''}, {key: '', value: ''}],
info: '',
meshes: [],
}
.....so on....
]
So from above data i want to check if each attributes has key and value empty or undefined. how can i check that. could someone help me with this. thanks.
Here's similar SO post.
Try the following codes below:
function isEmptyObject(o) {
return Object.keys(o).every(function(x) {
return o[x]===''||o[x]===null; // or just "return o[x];" for falsy values
});
}
or
const isEmpty = Object.values(object).every(x => (x === null || x === ''));
Firstly, iterate over data, then, check length of attribute array
data.forEach(attr => {
if(attr.length > 0){
// attr contains key and value
}
})
for (let x in data) {
for (let y in data[x].attributes) {
if ((key === '') || (value === '')) {
return ('data:' + x + 'attribute:' + y + 'missing key or value');
}
}
}
Untested.
Loops through all data and attributes to test for empty key/value. You can add an extra else if to check for value and key separately.

JavaScript - Filter object based on multiple values

I need to filter some data based on multiple values. Language, title and slug
[
{
de: "4567uy55",
en: "654321",
lang: [
{
id: "654321",
language: "English",
title: "Title1"
},
{
id: "4567uy55",
language: "German",
title: "Title2"
}
],
slug: 'some-slug'
},
...
]
What I have now returns all objects which have one or part of the filters(in case title is This is a title, the word this should match), but I need to return objects which have all of them.
I used an object flattner just to get all properties and values in one object, but I can't get it to filter the way I need it.
multiFilter = (arr, filters) => {
console.log(filters)
console.log(arr)
let newArray = []
for (let c of arr) {
let flatCourse = flatten(c)
for (let k in flatCourse) {
const keyArr = k.split('/')
const filterKeys = Object.keys(filters)
Object.keys(filters).map((key) => {
if (keyArr.includes(key)) {
const flatVal = flatCourse[k].toString().toLowerCase()
const filterVal = filters[key].toString().toLowerCase()
console.log(flatVal)
console.log(filterVal)
if (flatVal.includes(filterVal)) {
arr = []
arr.push(c)
newArray.push(c)
}
}
})
}
}
return newArray
}
Filters look like this:
[
language:["English"],
title: ["Some title"],
slug:["some slug"]
]
Instead of mixing for loops and functional chaining you could just go with one of them:
multiFilter = (arr, filters) =>
arr.map(flatten).filter(el => // filter out elements from arr
Object.entries(filters).every(([fKey, fValues]) => // ensure that every key is included in the object
Object.entries(el).some(([oKey, oValue]) =>
oKey.split("/").includes(fKey) && fValues.includes(oValue)// make sure that at least one of the values equals the elements value
)
)
);
arr.filter(course => {
// Returns an array of booleans corresponding to whether or not each filter condition is satisfied
return Object.keys(filters).map(key => {
return filters[key].map(filter => {
// Special case here because lang is an array
if (key == 'language' && course.lang != undefined) {
return course.lang.some(lang => lang[key].includes(filter))
}
if (course[key] == undefined) {
return false
}
return course[key].includes(filter)
}).every(result => result == true)
}).every(result => result == true)
})

Categories

Resources