How to print objects except one, without deleting anything (JavaScript) [duplicate] - javascript

This question already has answers here:
Filter object properties by key in ES6
(30 answers)
Closed 3 years ago.
So i want to filter object of objects, and print all of them except one, which i specify by key.
const obj = {1: {age: 10}, 2: {age: 20}};
console.log(obj);
So i must have option to somehow specify that i don't want the obj[1] to be printed. How do i do that? : |
I don't want to delete anything from it.

You could destructure the object:
const obj = {1: {age: 10}, 2: {age: 20}, 3: {age: 30}},
key = 1;
const { [key]:_, ...rest } = obj
console.log(rest);

You can filter() the keys and then convert it back to object using reduce()
const obj = {1: {age: 10}, 2: {age: 20}};
let key = 1
console.log(Object.keys(obj).filter(x => x != key).reduce((ac,a) => ({...ac,[a]:obj[a]}),{}));
Using the new feature Object.fromEntries
const obj = {1: {age: 10}, 2: {age: 20}};
let key = 1
let res = Object.fromEntries(Object.entries(obj).filter(x => x[0] != key));
console.log(res);

Related

What is the most efficient way to update a key inside of an array of objects in Javascript? [duplicate]

This question already has answers here:
JavaScript: Object Rename Key
(35 answers)
Closed 1 year ago.
If I have a JavaScript array including 10 objects with the following syntax:
const myArray = [{Age: 10, Name: Justin}, {Age: 15, Name: Bob}, ..., {Age: 20, Name: Jon}];
What's the most efficient way to update the Name key to be DisplayName. This is my currently logic:
myArray = myArray.map(item=>{return {age:item.age, displayName:item.name }});
I think your logic is fine but can be shortened.
myArray = myArray.map(({ age, name }) => ({ age, displayName: name }));
It can be done by shallow copy and use spread operator to rename key of object
const arr = [{Age: 10, Name: 'Justin'}, {Age: 15, Name: 'Bob'}, {Age: 20, Name: 'Jon'}];
function renameKey(obj, oldName, newName) {
const { [oldName]: val, ...rest } = obj
return {
...rest,
[newName]: obj[oldName]
}
}
const res = arr.map(i => {
const tmp = renameKey(i, 'Name', 'displayName')
return tmp
})
console.log('result ~> ', res)
or with lodash
const arr = [{Age: 10, Name: 'Justin'}, {Age: 15, Name: 'Bob'}, {Age: 20, Name: 'Jon'}];
const res = _.map(arr, function(i) {
return _.mapKeys(i, function(val, key) {
return key === 'Name' ? 'displayName' : key
})
})
console.log('res ~> ', res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
If you want to update the original Array, never use map. Because map is used to create a new Array from an existing one.
Instead loop through the nodes in Array. Create tehe new node with key displayName and delete the key Name.
Working Fiddle
const myArray = [{Age: 10, Name: 'Justin'}, {Age: 15, Name: 'Bob'}, {Age: 20, Name: 'Jon'}];
myArray.forEach((node) => {
node.displayName = node.Name;
delete node.Name;
});
console.log(myArray);

How to find occurence of objects in an array

I need to know if an array of objects contains at least two same objects in it, in JavaScript.
I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.
// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]
I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.
Separate objects are never === to each other, so you'll have to use a different method. One option is to create a Set of the stringified objects, and return true once any duplicate string is found:
const hasDupes = (arr) => {
const strings = new Set();
for (const obj of arr) {
const string = JSON.stringify(obj);
if (strings.has(string)) {
return true;
}
strings.add(string);
}
return false;
};
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]));
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]));
If you are only concerned about the value property and you use case is not more complex and you can simply do this in one line via:
let hasDupes = arr => new Set(arr.map(x => x.value)).size !== arr.length
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'},{value: 'a'}]))
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]))
You would use Set to add the values of value and if the size of it is smaller than the actual input array length than you had duplicates. There is no need to do JSON.stringify, compare strings etc if you only care about that one property being checked.
Also JSON.stringify has issues when comparing equality of objects.
Use findIndex:
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}];
const index = array.findIndex(({ value }) => value == "a");
console.log(index);
indexOf will return the instance of an object
{value: 'a'} !== {value: 'a'};
as they are both different instances of objects.
You can find the object
const obj = array.find(item => item.value === 'a')
You can use lodash.js to compare two objects.
Please see the sample below.
let array = [{ value: "a" }, { value: "b" }, { value: "c" }, { value: "a" }];
const object = { value: "a" };
countObjOccurrences = object => {
let occurances = 0;
array.map(item => {
if (_.isEqual(item, object)) {
occurances += 1;
}
});
return occurances;
};
This function will return 2.

JS Search in object array by using array [duplicate]

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 3 years ago.
I want to remove all the object from a data array that contains the same id in an array of id. How can I achieve this task without looping it?
const id = [1, 2];
const data = [
{id: 1},
{id: 2},
{id: 3}
];
console.log(data);
You can try with Array.prototype.filter()
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
and Array.prototype.includes():
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.
const id = [1, 2];
const data = [
{id: 1},
{id: 2},
{id: 3}
];
var res = data.filter(i => !id.includes(i.id));
console.log(res);
let newData = data.filter(item => !id.includes(item.id));
console.log(newData);
You can use .filter() and .includes() for filtering your object.
const id = [1, 2];
let data = [
{id: 1},
{id: 2},
{id: 3}
];
data = data.filter((item) => (!id.includes(item.id)));
console.log(data);
You can use method uniqBy from lodash https://lodash.com/docs/4.17.11#uniqBy
const uniqArray = _.uniqBy([{ 'id': 1 }, { 'id': 2 }, { 'id': 1 }], 'id');
console.log(uniqArray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

compare array of objects

Compare Array of Objects
function compare (arr1, arr2){
//if object key value pair from arr2 exists in arr1 return modified array
for (let obj of arr2) {
if(obj.key === arr1.key){
return obj
}
}
}
// Should return [{key: 1, name : "Bob", {key: 2, name : "Bill"}]
compare([{key: 1}, {key: 2}],
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])
I am having a disconnect with looping arrays of objects with different lengths and properties. I have tried looping and IndexOf but due to different lengths, I cannot compare the two arrays that way. I feel like a filter might be a good tool but have had no luck. Any thoughts?
Create a Set of properties from the 1st array (the keys), and then Array#filter the 2nd array (the values) using the set:
function compareBy(prop, keys, values) {
const propsSet = new Set(keys.map((o) => o[prop]));
return values.filter((o) => propsSet.has(o[prop]));
}
const result = compareBy('key', [{key: 1}, {key: 2}],
[{key: 1, name : "Bob"}, {key: 3, name : "Joe"}, {key: 2, name : "Bill"}])
console.log(result);

how to prevent sequence when i use Array.forEach [duplicate]

This question already has answers here:
Sort JavaScript object by key
(37 answers)
Closed 6 years ago.
const a = {};
array.forEach(item => {
a[item.id] = item;
})
when i get a, I found it was sort by item.id. How to prevent the sort when forEach.
if array = [{id: 2}, {id: 6}, {id : 1}], and then I get a = {1: {id: 1}, 2: {id: 2}, 6: {id: 6}}.
my want is a={2: {id: 2}, 6: {id:6}, 1: {id: 1}}
I don't think you can enforce a particular object key sequence in JS. You can, however, create an array of the keys.
const a = {};
const originalSequence = [];
array.forEach(item => {
a[item.id] = item;
originalSequence.push(item.id);
})

Categories