Take elements by key in objects array - javascript

Let's say I have got an array of objects like this:
const a = [
0: {name: 'John', lastName: 'Smith'}
1: {name: 'Juan', lastName: 'Perez'}
myKey: true
myKey2: false
]
How can I extract from my array just the value of 'myKey'?
So the expected output would be
const myKeyValue = true

If you want a single value and you know the key, use:
const myKeyValue = a.myKey

Related

JS create new array from certain item

I have 2 dimensional array myArray:
[
[ '567576', 'John', 'Doe' ],
[ '098897', 'John', 'Doe' ],
[ '543539', 'John', 'Doe' ],
[ '234235', 'John', 'Doe' ],
[ '345348', 'John', 'Doe' ],
[ '432574', 'John', 'Doe' ]
]
Is it possible to create a new array from myArray starting from a certain first value?
For example create a new array starting from id 543539. Anything above the array containing 543539 will not be added.
You can make use of findIndex() which returns the index of the first item that matches the condition.
Combine it with slice() to cut your array at the specific position:
const myArray = [
['567576', 'John', 'Doe'],
['098897', 'John', 'Doe'],
['543539', 'John', 'Doe'],
['234235', 'John', 'Doe'],
['345348', 'John', 'Doe'],
['432574', 'John', 'Doe']
]
console.log(myArray.slice(myArray.findIndex(item => item[0] === "543539")));
Sure, assuming all the internal arrays are structured the same way, you can do something like let newArray = myArray.filter(innerArray => Number(innerArray[0]) > 543539)
Edit: This is assuming you want all subarrays where the first item is a number larger than 54539, as opposed to finding all of the subarrays that physically follow the first occurrence of a subarray with 54539 as the first value
Yes, that is possible and straightforward process.
You can use the javascript map method which returns a new array
newArray = myArray.map(item=> item[0])

Accessing duplicates in objects in the same array?

I have an array with multiple objects
arr = [
{name: 'xyz',
age: 13,
},
{name: 'abc',
age: 15,
},
{name: 'abc',
age: 15,
}]
how do I find the duplicate in this array and remove the object that is duplicated in the array? They are all in one array.
Apologies. I just realized what I am trying to do is, remove the object entirely if there's a duplicate in one key... so if the age is similar, I will remove object name "def". Is this possible?
arr = [
{name: 'xyz',
entry: 1,
age: 13,
},
{name: 'abc',
entry: 2,
age: 15,
},
{name: 'def',
age: 13,
entry: 3
}]
You could achieve this by the following steps:
transform each element into an object that is key-sorted, this will make objects consistent in terms of key-value pairs order, which will help us in the next step
map the array into JSON-stringified value, and store it into a Set(), which would help us store only unique stringified objects
turn the Set() back into array
map the array back into objects by JSON.parse() each element
const arr = [
{ name: "xyz", age: 13 },
{ age: 15, name: "abc" },
{ name: "abc", age: 15 },
]
const sortKeys = obj =>
Object.fromEntries(
Object.entries(obj).sort((keyValuePairA, keyValuePairB) =>
keyValuePairA[0].localeCompare(keyValuePairB[0])
)
)
const res = Array.from(
arr
.map(sortKeys)
.map(el => JSON.stringify(el))
.reduce((set, el) => set.add(el), new Set())
).map(el => JSON.parse(el))
console.log(res)
References
Set
Object.entries()
Object.fromEntries()

Lodash. How to get array values from object if you know array keys?

For example, you have an object.
{ id: 1, firstName: 'John', lastName: 'Doe' }
How to get an array from the object if you know array keys? You have array keys
['firstName', 'lastName']
and you should get array
['John', 'Doe']
I use Lodash.
You can you _.at():
const obj = { id: 1, firstName: 'John', lastName: 'Doe' };
const keys = ['firstName', 'lastName'];
const result = _.at(obj, keys);
console.log('RESULT:', result);
<script src='https://cdn.jsdelivr.net/lodash/4.16.6/lodash.min.js'></script>
You don't need lodash.
Just use Array.prototype.map to get values from key array.
const obj = { id: 1, firstName: 'John', lastName: 'Doe' };
const filterKey = ['firstName', 'lastName'];
console.log('FILTERED:', filterKey.map(key => obj[key]));
const keys = Object.keys({ id: 1, firstName: 'John', lastName: 'Doe' });
const values = Object.values({ id: 1, firstName: 'John', lastName: 'Doe' });
console.log(keys)
console.log(values)
You don't need to use Lodash, using plain javascript will do it.
Use Object.keys() for getting all the keys of an object and Object.values() to get an array with all the values that an object has.

How to take an array of objects and create arrays based on property values?

I have an array of objects and trying to take thevalues inside those objects and push them into an array based on the same property value. So for example.
array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
I have this array of objects and now I want to iterate through it and create arrays with all name values and age values. The array also needs to be the same name as the values. So the result will be.
name = ['John', 'Lily']
age = [12, 22]
How would I be able to do this?
Just map over the array like so:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
]
const name = array.map(e => e.name);
const age = array.map(e => e.age);
console.log(name);
console.log(age);
EDIT
If the array has dynamic objects, you can do this:
const array = [
{name: 'John', age: 12},
{name: 'Lily', age: 22}
];
for (var key in array[0]) {
window[key] = array.map(e => e[key]);
}
console.log(name);
console.log(age);

how to add an object with two pairs to an array that has a key and values that are same as the object

I need to build an array based on server data. I get the data as an object like this:
{name: "test", hobby: "test"}
and my array that I want to add this object to looks like this:
[0: {name: "test1", hobby: "test1"}, 1 : {name: "test2", hobby: "test2"}]
output should be:
[0: {name: "test1", hobby: "test1"}, 1 : {name: "test2", hobby: "test2"}, 2 : {name: "test", hobby: "test"}]
How do I add the element to the array? Push did not work in this case. I need to add the key to the element and then add it to the end of array but I don't know how.
Please let me know what are the options.Thanks.
if you want to add key, you should use object.
like
let obj = {};
function addData(){
let length = Object.keys(obj).length
temp = {name:"test"+(length+1),hobby:"test"+(length+1)}
obj[length]= temp;
console.log(obj);
}

Categories