Retrieve string from object using Object.keys - javascript

An object which contains 4 string, from this object i need the data one by one i have tried Object.keys(Object_name).[index] but data couldn't retrieve.
this is the object:
Object_name={
0: "A",
1: "R",
2: "E",
3: "A"
}
Thanks in advance.

Object.keys(Object_name) will print [0, 1, 2, 3] so if you do Object.keys(Object_name)[0] you'll get 0, 1 for 1 etc ... [0, 1, 2, 3][0] => 0 if you get undefined define your object_name
As far as I understand you want to loop on object name and get every Object value using Object keys
Object.keys(Object_name).forEach(key => { console.log(Object_name[key]); });
To read more about Object.keys

Use Object.entries:
Object_name={
0: "A",
1: "R",
2: "E",
3: "A"
}
Object.entries(Object_name).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});

Related

Can I combine spread and rest in destructuring object in Javascript?

Let us have this object:
// Values of properties are irelevant
let row = {_x: "x", _y: "y", _z: "z", a: "a", b: "b"}
I need to get copy of this object without properties beginning with underscore (_).
I can do this:
const {_x, _y, _z, ...pureRow} = row;
console.log(pureRow); // {a: "a", b: "b"}
But I would like to have a list of removed properties in an array and remove all properties listed in this array. Something like:
const auxFields = ["_x", "_y", "_z"];
const {...auxFields, ...pureRow} = row; // Error: A rest element must be last in a destructuring pattern.
console.log(pureRow); // {a: "a", b: "b"}
Is there some way to achieve this?

How to obtain the object values from an array with one object and create a new array with just the object values

Given the following array with just one object:
let myVar = [
{
"v1": "A",
"v2": "B",
"v3": "C",
"v4": "D"
}
]
How can I create a new array with just the object values alone from the above myVar array, i.e. the newArray should now be:
let newArray = [ "A", "B", "C", "D" ]
Just unsure how to solve this.
If you know for sure that it will only have one object then all you need to do is:
Object.values(myVar[0])
see docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Note: If you need to support older browsers like internet explorer you will have to use Object.keys paired with map
Try This,
You get the result you want.
let newArr = [];
for (var key in myVar[0]) {
if (myVar[0].hasOwnProperty(key)) {
newArr.push(myVar[0][key]);
}
}
console.log('New Array: ',newArr);
Output: [ 'A', 'B', 'C', 'D' ]
There are 2 ways I can think of:
Using for...in statement: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
let newArray = [];
for (const property in myVar[0]) {
newArray.push(object[property]);
}
Or using Object.entries() method combining with for...in: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
You can use reduce method with spread syntax if your array has multiple Object.
const newArray = myVar.reduce((acc, curr) => {
return [...acc, ...Object.values(curr)];
}, [])
console.log(newArray)
You can use Object.values to get all values of an object
The Object.values() method returns an array of a given object's own
enumerable property values
let myVar = [{
v1: "A",
v2: "B",
v3: "C",
v4: "D",
}, ];
const newArray = Object.values(myVar[0]);
console.log(newArray);
Provided that the array has just one object, you can simply assign Object.values of that particular object to a new variable.
Array.prototype.values() method returns a new Array Iterator object that contains the values for each index in the array. Reference
let myVar = [
{
"v1": "A",
"v2": "B",
"v3": "C",
"v4": "D"
}
]
const newArr = Object.values(myVar[0]);
console.log(newArr);

How can I use the values of array A as keys to address multidimensional array B in javascript? [duplicate]

This question already has answers here:
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Closed 3 years ago.
EDIT: The supposed "duplicate" question "Convert JavaScript string in dot notation into an object reference" is completely different than my question as explained using the example I provided.
Aside the question itself, the provided arrays are in a completely different format than mine.
The fact that the solution is similar doesn't mean that the question is a duplicate(!) you should know better than that -before downvoting the question (is this voting done by a webbot? it's too stupid for a human) -which doesn't make a difference for me anyway as I got the solution. It only damages the reputation of StackOverflow.
Example:
I have array A and array B:
var A = [2, 4, 4, 2];
var B =
["t1",
"a",
["t2",
"a",
"b",
["t3",
"a",
"b"
],
["t4",
"a",
"b",
"c",
["t5",
"a",
"b"
]
],
],
["t6",
"a",
"b",
["t7",
"a",
"b"
]
]
]
and I want to use each elements of the unidimensional array A as keys in that exact sequence, in order to address the multidimensional array B as bellow:
var val = B[2][4][4][2].
How can I do that efficiently?
I only found a solution for PHP, not javascript.
Use Array.reduce() on array A, and use array B as the initial value:
const A = [2, 4, 4, 2];
const B = ["t1",
"a", ["t2",
"a",
"b", ["t3",
"a",
"b"
],
["t4",
"a",
"b",
"c", ["t5",
"a",
"b"
]
],
],
["t6",
"a",
"b",
["t7",
"a",
"b"
]
]
]
const result = A.reduce((r, c) => r[c], B)
console.log(result)

Destructuring for get the first property of an object?

For arrays, we can define the properties depending on it's indexes like:
const arr = [1, 2, 3];
const [first, second, third] = arr;
console.log(first, second, third)
I'm just wondering if there's a possible solution to do it's reverse with objects like:
const obj = {first: "a", second: "b", third: "c"}
const {0, 1, 2} = obj;
//expected: "a", "b", "c"
You do it like this for objects:
const obj = {foo: 123, bar: 'str'}
const {foo, bar} = obj
It isn't.
Objects are not designed to be ordered, so there isn't a first property per se.
You could convert an object into an array of its values first …
const obj = {
first: "a",
second: "b",
third: "c"
}
const array = Object.values(obj);
const [foo, bar, baz] = array;
console.log({
foo,
bar,
baz
});
… but it is unlikely to be useful and it certainly wouldn't be intuitive code that is easy to maintain.
Try this:
const obj = {first: "a", second: "b", third: "c"}
const indexes = [0, 1, 2]
indexes.map( (val) => { return Object.values(obj)[val] } ) //["a", "b", "c"]
You could take the values and assign this to an array for destructuring.
The order is actually dtermined by the insertation order or if a key is like a valid index of an array, it is sorted numerically to top.
const
object = { first: "a", second: "b", third: "c" },
[first, second, third] = Object.values(object);
console.log(first, second, third);
For extracting a an arbitrary position, you vould take an object with an index an object property assignment pattern [YDKJS: ES6 & Beyond] for a new valid variable.
const
object = { first: "a", second: "b", third: "c" },
{ 2: foo } = Object.values(object);
console.log(foo);

Convert an array to nested object using Lodash, is it possible?

I have an array:
["a", "b", "c", "d"]
I need to convert it to an object, but in this format:
a: {
b: {
c: {
d: 'some value'
}
}
}
if var common = ["a", "b", "c", "d"], I tried:
var objTest = _.indexBy(common, function(key) {
return key;
}
);
But this just results in:
[object Object] {
a: "a",
b: "b",
c: "c",
d: "d"
}
Since you're looking for a single object out of an array, using _.reduce or _.reduceRight is a good candidate for getting the job done. Let's explore that.
In this case, it's going to be hard to work from left to right, because it will require doing recursion to get to the innermost object and then working outward again. So let's try _.reduceRight:
var common = ["a", "b", "c", "d"];
var innerValue = "some value";
_.reduceRight(common, function (memo, arrayValue) {
// Construct the object to be returned.
var obj = {};
// Set the new key (arrayValue being the key name) and value (the object so far, memo):
obj[arrayValue] = memo;
// Return the newly-built object.
return obj;
}, innerValue);
Here's a JSFiddle proving that this works.

Categories

Resources