Get first 5 key value from object [duplicate] - javascript

This question already has answers here:
Clone a object JSON but until its 5th key-value
(2 answers)
Closed 1 year ago.
Suppose I have an object with 10 key values,
const detail = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10}
I only want to get first 5 key values from object,
**{'a':1,'b':2,'c':3,'d':4,'e':5}**
Like we can slice in array and get first 5 elements, is it possible to do something for the same.
I tried looking for solution, but was unable to find anything related to it.
Any help would really be helpful. If anyone needs any moew details please let me know.

You can get an array of the object's entries (key-value pairs in the form of an array), then slice that array and turn it back into an object:
const detail = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10};
const sliced = Object.fromEntries(
Object.entries(detail).slice(0, 5)
);
console.log(sliced);

Use Object.fromEntires with Object.entries
Object.entries will return a nested array of key, value pairs, which you can slice and then pass that slice to Object.fromEntries which will return an object.
const detail = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10 };
const res = Object.fromEntries(Object.entries(detail).slice(0, 5));
console.log(res);

Related

js: add element at the start of an array [duplicate]

This question already has answers here:
How can I add new array elements at the beginning of an array in JavaScript?
(12 answers)
Closed 10 months ago.
Let´s say I have this array:
let array = ["somevalue", "anothervalue"]
So what I wanted to da was to add a value, for example:
let foo = {bar: true} and add this value at index 0, but not overwrite the old value, rather kind of 'push' the rest of the values back. I´ve heard of array = [foo, ...array] but I am not quite sure what it does and how and when to use it.
Anyone any ideas?
let array = ["somevalue", "anothervalue"]
let foo = {bar: true}
array.unshift(foo);
console.log(array); // prints [{bar: true}, "somevalue", "anothervalue"]
Similarly, the shift() method removes the first item in the array.
It simply append the foo in front of array. so array will become
[{bar: true}, "somevalue", "anothervalue"]
Alternate :
You can also use unshift, it also append data at index 0, eg.
let array = [2, 3, 4]
array.unshift(1)
console.log(array) /// output : [1, 2, 3, 4]
Ok,
let arr = [1,2]
let foo={bar:true}
arr=[foo].concat(arr)
also what you already know works
arr=[foo, ...arr]
That's it

How to push all the values in array? [duplicate]

This question already has answers here:
Copy array items into another array
(19 answers)
Closed 2 years ago.
I have this:
z: [[res.push(this.Map.heatmap[0])]],
so this is just one value. But how can I push all the values of the array
and this is the interface:
export interface map {
}
I have a array of 100 values in it:
10
but if I do this:
this.Map().subscribe((res) => {
zsmooth: 'best'
}
],
not all the values are loaded. So how to load all the values?
and this is how I have the object:
Map: map = {};
Thank you
Oke,
console.log(res)
gives back array with 100 values:
length: 100
but apperently this:
z: [[res]],
doesn't work. I dont see the value at all.
But if I do this:
hallo: console.log(res.push(this.Map.map[0])),
z: [[res.push(this.cMap.tmap[0])]],
it returns the number 2
concat function is maybe what you are looking for:
var array1 = [A, B, C];
var array2 = [D, E, F];
var newArray = array1.concat(array2);
The newArray will be [A,B,C,D,E,F]
In your case you would do something like:
z = z.concat(this.cameraAgretateHeadMap.heatmap)
a little bit more code from your side would have been helpful to understand it in a better what your problem is!
Hopefully this helps!

Assign the same array object to multiple variables? [duplicate]

This question already has answers here:
javascript for loop changes original list variable
(3 answers)
Closed 2 years ago.
From what I understand, when an array object is assigned to a new variable, that array object can be "referenced" between both variables, but the values themselve are mutable by either assigned variable.
At least that appears to be the case.
let variable1 = [6, 3, 2, 6, 7, 2, 9, 1, 5];
let variable2 = variable1;
for (i = 0; i < 10; i++) {
variable2.unshift(i);
}
console.log(variable1);
> [9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 6, 3, 2, 6, 7, 2, 9, 1, 5]
Am I only able to timestamp the state of my data at a given point in the run time by creating a new array and pushing in the contents of the previous array, or is there another practice used? Thanks.
Array.from()
const array2 = Array.from(array1)
console.log(array2)
If you don't want this behaviour, you have to make sure to use methods that generate a new array on every mutation of the original array.
To copy an array you can use Array.from(array) or ES6 [...array].
With that knowledge: For array.unshift(e) you can use ES6 array = [...array, e];
let variable1 = [6, 3, 2, 6, 7, 2, 9, 1, 5];
let variable2 = variable1;
for (i = 0; i < 10; i++) {
variable2 = [...variable2, i];
}
console.log('var2', variable1);
console.log('var1', variable2);
Javascript generally is always pass by value, but in the case when the variable refers to an object (including arrays) the "value" is a reference to that object.
When you change the value of a variable, it doesn't change the underlying object or primitive - instead it just points the variable to the new value.
However changing properties on an object (including arrays) will change the underlying object itself.
tl;dr
There is no way to capture the state at a given timepoint without making a complete copy of it.
How to create the copy
Depending on how your data is structured there are multiple ways you could go about to create a clone of it.
If it is just an array of primitives, e.g. an array of numbers / strings, a shallow copy of the array would suffice:
const arr = [1,2,3,"foo"];
// using array spread
const clone1 = [...arr];
// Array.from()
const clone2 = Array.from(arr);
// mapping the array
const clone3 = arr.map(e => e);
// push with spread
const clone4 = [];
clone4.push(...arr);
// good old for loop
const clone5 = [];
for(let i = 0; i < arr.length; i++)
clone5.push(arr[i]);
If you have a deep data structure with nested objects / arrays, you need to do the shallow copying recursively to achieve a deep copy.
However there are already lots of good libraries that can handle these for you, for example lodash:
const value = [{a: 1}, {b: 2}, {c: ["a", "b"]}];
// using lodash _.cloneDeep to get a deep copy
const clone = _.cloneDeep(value);

How can I sort after an array's second value within an array? [duplicate]

This question already has answers here:
Sorting object property by values
(44 answers)
Closed 3 years ago.
I want to manipulate an object {a: 1, b: 20, c: 3, d: 4, e: 1, f: 4} into this {a: 1, e: 1, c: 3, d: 4, f: 4, b:20} (sorting the object numerically in ascending order) in these specific steps (I am aware that there must be easier, more advanced ways):
Defining a function called 'sort' which takes an object as argument and inside it declaring an empty array called 'arr'.
Looping inside the object and for each iteration push an array which contains the key and the value to 'arr'.
Sorting the array numerically by the object value (position one in our nested arrays)
Creating an empty object called 'newObj'.
Looping through the array and for each iteration assign the first and second element as the key and value respectively to our 'newobJ'
Returning the 'newObj'.
This is what I have so far. The code has hickups at the sorting parts but maybe also other things I am not yet aware of.
function sort(object) {
var arr = []
var newObj = {}
Object.entries(object).forEach(function(element, index) {
arr.push(element)
})
arr[index][1].sort(function(a, b){return b-a});
arr.forEach(function([key, value], index) {
newObj[key] = value
})
return newObj
}
How do I need to improve my code to make the function work?
You could take the entries, sort by the second index and get a new object.
var object = { a: 1, b: 20, c: 3, d: 4, e: 1, f: 4 },
result = Object.fromEntries(
Object
.entries(object)
.sort((a, b) => a[1] - b[1])
);
console.log(result);
By taking your algorithm,
arr[index][1].sort(function(a, b){return b-a});
you need to sort the complete array by
arr.sort(function (a, b) { return a[0] - b[0]; });
Array#sort takes a callback and this has two parameters, one for each item and returns a value which reflects the wanted order of the two elements.
In this case, by taking an array of entries, you have for example two arrays as parameter, like
['a', 1]
['b', 20]
from this arrays take the value from index 1 and return the delta of it.

Typescript - Keep only specific object keys [duplicate]

This question already has answers here:
One-liner to take some properties from object in ES 6
(12 answers)
Closed 5 years ago.
I have an object with some keys
{
a: 1,
b: 2,
c: 3,
.....
}
I'm looking for the easiest way to keep only specific keys from the object
For example I want to clone this object and keep only "a" and "b"
The first object doesn't have specific keys, so I can't just delete "c"
I'm looking for the easiest way
Thanks
You can use .reduce on Array of keys (as strings).
You can check for .hasOwnProperty to validate the existing of the key before adding it to the new object.
Example:
const obj = {
a: 1,
b: 2,
c: 3,
}
const newObj = ['a', 'c', 'z'].reduce((result, key) => {
if (obj.hasOwnProperty(key)) {
result[key] = obj[key];
}
return result;
}, {});
console.log(newObj)

Categories

Resources