javascript Collection of an object accessible by key [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
How can I make this happen in javascript??
People[key1][0].FirstName = "First1-k1";
People[key1][0].LastName = "Last1-k1";
People[key1][1].FirstName = "First2-k1";
People[key1][1].LastName = "Last2-k1";
People[key2][0].FirstName = "First1-k2";
People[key2][0].LastName = "Last1-k2";
People[key2][1].FirstName = "First2-k2";
People[key2][1].LastName = "Last2-k2";
Or maybe:
People[key2].Index[1].LastName = "Last2-k2";
Other clarification:
SomeObject["somekey"][0].FirstName = "whatever";
SomeObject["somekey"][1].FirstName = "whatever";
SomeObject["someotherkey"][0].FirstName = "whatever";
SomeObject["someotherkey"][1].FirstName = "whatever";
Thanks

When using properties and indexes together, you are talking about Objects (which have properties) and Arrays (which have indexes).
Your initial syntax of: People[key1], implies that People is either an array where key1 is a variable holding a non-negative number or People is an Object where key1 is a string the will serve as the name of a property of the object.
So, you could have:
var People = ["John","Paul","Ringo","George"];
var key1 = 3; // Arrays use non-negative numbers as indexes
console.log(People[key1]); // "George"
Or, you could have:
var People = {
first:"John",
last: "Lennon"
}
var key1 = "first"; // Objects use strings as property names
console.log(People[key1]); // "John"
Now, if we continue your code: People[key1][0], you indicate that key1 should be indexed with a number, so that means that People[key1] should return an Array. This would mean that People could be an array containing arrays or an Object with arrays as properties:
Array with nested arrays:
var People = [
["John","Paul","Ringo","George"],
["Moe","Larry","Curly","Shemp"]
];
var key1 = 1;
console.log(People[key1][0]); // "Moe"
Object with arrays as property values:
var People = {
Beatles: ["John","Paul","Ringo","George"],
ThreeStooges: ["Moe","Larry","Curly","Shemp"]
};
var key1 = "Beatles";
console.log(People[key1][0]); // "John"
Finally, when we add your last pieces of syntax: People[key1][0].FirstName, we can see that People[key1][0] must be returning an Object because you are providing a property name to access, so the final structure could still use Array or Objects, but could look like these:
Array with nested arrays that hold objects that have properties:
var People = [
[
{ firstName: "John" },
{ firstName: "Paul"} ,
{ firstName: "Ringo"} ,
{ firstName: "George"}
],
[
{ firstName:"Moe", lastName: "Stooge" },
{ firstName: "Larry", lastName: "Stooge" },
{ firstName: "Curly", lastName: "Stooge" },
{ firstName:"Shemp", lastName: "Stooge" }
]
];
var key1 = 1;
console.log(People[key1][0].firstName); // "Moe"
People[key1][0].firstName = "First-K2";
console.log(People[key1][0].firstName); // "First-K2"
Object with arrays as property values that store objects which have properties:
var People = {
Beatles: [
{ firstName: "John" },
{ firstName: "Paul"} ,
{ firstName: "Ringo"} ,
{ firstName: "George"}
],
ThreeStooges: [
{ firstName:"Moe", lastName: "Stooge" },
{ firstName: "Larry", lastName: "Stooge" },
{ firstName: "Curly", lastName: "Stooge" },
{ firstName:"Shemp", lastName: "Stooge" }
]
};
var key1 = "Beatles";
console.log(People[key1][0].firstName); // "John"
People[key1][0].firstName = "First-K2";
console.log(People[key1][0].firstName); // "First-K2"
Now, while your syntax could mean two different structures that both could work, you really need to spend some time and think about this from the inside out. You appear to have objects with a firstName property as the deepest construct in your structure, but working outward from there, you seem to just be adding layers without any particular reason. Should the objects with firstName properties be enumerable? If so, it makes sense to have them in an array. But, why package them up any further? You need to decide.

Related

How to filter few properties of an object which is in Array of objects if one property equals property from another object

I have a object which has some properties for one user, and I have array of objects which is returned from API.
My goal is to check which object of Array of objects has the same property as the one single initial object, and then it should return only part of it's properities.
I have tried to use .map on Array of objects but it seems not workig.
Below is the code example. I have also prepared codesandbox if You wish.
const user =
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
car: "audi"
}
;
const usersAnimal = [
{
name: "jan",
lastName: "kowalski",
fullName: "jan kowalski",
animal: "cat",
animalSize: "small",
animalName: "Bat"
},
{
name: "john",
lastName: "smith",
fullName: "john smith",
animal: "dog",
animalSize: "middle",
animalName: "Jerry"
},
{
name: "Anna",
lastName: "Nilsson",
fullName: "Anna Nilsson",
animal: "cow",
animalSize: "big",
animalName: "Dorrie"
}
];
const filtered = usersAnimal.map((userAnimal)=>userAnimal.fullName === user.fullName && return userAnimal.animalName & userAnimal.animalSize & userAnimal.animal);
thanks
https://codesandbox.io/s/admiring-edison-qxff42?file=/src/App.js
For case like this, it would be far easier if you filter it out first then proceed using map:
const filtered = usersAnimal
.filter((animal) => animal.fullName === user.fullName)
.map(({ animalName, animalSize, animal }) => {
return {
animalName,
animalSize,
animal
};
});
I am providing a for loop solution as I haven't learnt many array methods in javascript.
For me the simplest option is to use a for loop and an if check to loop through the arrays values to check for included values.
for (let v in usersAnimal) {
if (usersAnimal[v].fullName === user.fullName) {
console.log(usersAnimal[v])
}
}
The code above will log the entire usersAnimal object containing the fullname we are looking for.
{
name: 'jan',
lastName: 'kowalski',
fullName: 'jan kowalski',
animal: 'cat',
animalSize: 'small',
animalName: 'Bat'
}
commented for further understanding
for (let v in usersAnimal) {
//loops though the array
if (usersAnimal[v].fullName === user.fullName) {
//when the index value 'v' has a fullname that matches the user fullname value
// it passes the if check and logs that object value
return console.log(usersAnimal[v])
//return true...
}
//return null
}
//etc
If you want to filter, I recommend you to use filter.
The map method will create a new array, the content of which is the set of results returned by each element of the original array after the callback function is operated
const user = {name:"jan",lastName:"kowalski",fullName:"jan kowalski",car:"audi"};
const usersAnimal = [{name:"jan",lastName:"kowalski",fullName:"jan kowalski",animal:"cat",animalSize:"small",animalName:"Bat"},{name:"john",lastName:"smith",fullName:"john smith",animal:"dog",animalSize:"middle",animalName:"Jerry"}];
// Get an array of matching objects
let filtered =
usersAnimal.filter(o => o.fullName === user.fullName);
// You get the filtered array, then you can get the required properties
filtered.forEach(o => {
console.log(
'animal:%s, animalSize:%s, animalName:%s',
o?.animal, o?.animalSize, o?.animalName
);
});
// Then use map to process each element
filtered = filtered.map(o => {
const {animal, animalSize, animalName} = o;
return {animal, animalSize, animalName};
});
console.log('filtered', filtered);

get first 2 charater from an object using JS [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 1 year ago.
i wanted represent first two letters of phone number,i want to get phone numbers first two characters. what i have tried is below Get first two of attribute and find target based on it.
let object = [
"key": {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}]
what i have tried is below
object[0].substr(0,2);
let test = {
key: {
"login-attempt": 1,
name: "ADMIN",
phone: "0777123456",
}
};
console.log(test.key.phone.substr(0,2));
You're more likely to have an object like this:
let object = {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
};
In this case, your code might be:
let prefix = object.phone.substr(0,2);
Or you might have an array of objects:
let object = [
{
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
},
{
login-attempt: 1
name: "CLERK"
phone: "2222222222"
}
];
You can get the 1st two characters of the second element like this:
let prefix = object[1].phone.substr(0,2);
If the element was nested within "key":
let object = {
key: {
login-attempt: 1
name: "ADMIN"
phone: "0777123456"
}
};
let prefix = object.key.phone.substr(0,2);
And so on...

Lodash merge object with nested array not working correctly

I found unexpected result when try to merge with lodash object with flat array inside.
Here the example:
var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };
const person = { age: '31', values: ["PT"] };
var people2 = { name: 'Andrew', age: '30', values: [{ pippo : 1}] };
const person2 = { age: '31', values: [{ pippo : 2}] };
// Now merge person back into people array
console.log(_.merge({}, people, person));
console.log(_.merge({}, people2, person2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
The result of first console.log is
{
age: "31",
name: "Andrew",
values: ["PT", "PORTA 31"]
}
And not as expected
{
age: "31",
name: "Andrew",
values: ["PT"]
}
Someone can explain me why and give me a solution to make sure that with a flat array it takes me the correct value
I think assign is better in this case than merge
This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
var people = { name: 'Andrew', age: '30', values: ["PT", "PORTA 31"] };
const person = { age: '31', values: ["PT"] };
console.log(_.assign({}, people, person));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
I believe _.assign(people, person) would produce the desired outcome in this case https://lodash.com/docs/4.17.15#assign
This functionality is also native and can be used like this Object.assign(target, source)

Loop over an object

I'm decoding an object and so far I got it working. Let's say I have this object:
var person = [{
firstname: "Mike",
lastname: "123ñññ"
age: 20
}]
So in order to decode &ntilde and render ñ, I'm simply doing this:
new DOMParser().parseFromString(person[0].lastname, "text/html").documentElement.textContent;
and this will render the value
ñññ
which is what I want, so it will look like this:
lastname: "ñññ"
However, the issue that I'm facing is that I need to decode values for each property in the object because I may get those special characters for firstname or other properties. So my question is how to decode property values on an object assuming that the object may look like this:
var person = [{
name: "Mike",
lastname: "123ñññ"
age: 20,
employeer: {
name: 'ABC Company ñê',
supervisors:[
{
name: 'Steveä',
code: 'è468'
}
]
}
}]
NOTE:
I don't need help on decoding that values of each property on my object, since I'm already doing that, I just need to come up with a recursive function that will do that on a nested object
I think a recursive decode using DOMParser is a good idea. Here's an in-place transformer. Perform a deep copy first and then transform in-place if you prefer.
var person = [{
name: "Mike",
lastname: "123ñññ",
age: 20,
employer: {
name: 'ABC Company ñê',
supervisors: [
{
name: 'Steveä',
code: 'è468'
}
]
}
}];
console.log(person);
function htmlDecode(input)
{
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
function fix(obj) {
for (let prop in obj) {
switch (typeof obj[prop]) {
case 'object':
fix(obj[prop]);
break;
case 'string':
obj[prop] = htmlDecode(obj[prop]);
break;
}
}
}
fix(person);
console.log(person);
in functional languages there are libraries to recursively walk tree scructures. In clojure there is the zipper and walk for example.
you could write it yourself but it will quickly get complicated so I suspect using JSON.stringify + parse would give you what you need. Both functions take second argument that's replacer and reviver respectively that allow you to intercept the transformations and alter the values.
Here is example from the official documentation:
function replacer(key, value) {
// Filtering out properties
if (typeof value === 'string') {
return undefined;
}
return value;
}
var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
JSON.stringify(foo, replacer);
// '{"week":45,"month":7}'
Try this:
function decodeObject(obj){
if(typeof obj == 'object'){
var text = JSON.stringify(obj),
div = document.createElement('div');
div.innerHTML = text;
obj = JSON.parse(div.childNodes[0].nodeValue);
}
return obj;
}
var person = decodeObject([{
name: "Mike",
lastname: "123ñññ",
age: 20
}]);
console.log(person);

Clone a object only with few properties

Is there a way to clone an object with only few properties of the object in JS?
For example..
var Person = {
name: "Bob",
age: 32,
salary: 20000
};
I have to create another person object with just the name and age property so that it will look something like this :
var clonedPerson = {
name: "Bob",
age: 32
};
I could do a deep clone of the object and delete. But I wanted to know if there are better ways to do it.
Using the latest ES6, you can achieve this by the following code..
const Person = {
name: "Bob",
age: 32,
salary: 20000
};
const { salary , ...clonedPerson } = Person
console.log(clonedPerson)
More simple?
var Person = {
name: "Bob",
age: 32,
salary: 20000
};
var ClonedPerson = jQuery.extend({}, Person);
delete ClonedPerson.salary;
console.log(JSON.stringify(Person));
console.log(JSON.stringify(ClonedPerson));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
an alternative approach using Array member methods:
var clone = Object.keys(Person) // convert to an Array of Person keys
.filter(function(key){return ["salary"].indexOf(key) == -1;}) // exclude key salary
.reduce(function(clone, current){clone[current] = Person[current]; return clone;}, {}); // convert back the array to a cloned literal object

Categories