0

I want to copy value of name and age into another array, below code is working fine, But I wanted to know better way to do it.

const users = [
    { id: 0, name: 'John', age:34 },
    { id: 1, name: 'Wayne', age:44 },
    { id: 2, name: 'David', age:24 },
];
let values=[];
 users && users.map(user => {
            values.push(user['name'])
            values.push(user['age'])

        })
        console.log(values);

output

['John', 34, 'Wayne', 44, 'David', 24]
5
  • "better" how? Commented Nov 9, 2022 at 8:19
  • with less code, in some standard way, instead of pushing, can we return Commented Nov 9, 2022 at 8:21
  • 1
    const values = (users) ? users.map(el => [el.name, el.age]).flat() : []; One line code, next time if you want a review of code use Code review Commented Nov 9, 2022 at 8:21
  • another alternative. simple and readable: const values = []; users.forEach(user => { values.push(user.name) values.push(user.age) }) Commented Nov 9, 2022 at 8:22
  • If your goal is to get less code, then use a minifier. Though I'd personally strive for readable and maintainable code. Commented Nov 9, 2022 at 8:25

2 Answers 2

3

You can bind each items to an array containing both its name and age and then flattern these arrays.

This can be done using Array#FlatMap

const users = [
    { id: 0, name: 'John', age:34 },
    { id: 1, name: 'Wayne', age:44 },
    { id: 2, name: 'David', age:24 },
];

const nameAndAges = users.flatMap(user => [user.name, user.age])

console.log(nameAndAges)

Sign up to request clarification or add additional context in comments.

Comments

0

Your solution looks good, this can be also solved in different ways, I guess you may want to create function for handling this.

const users = [
    { id: 0, name: 'John', age: 34 },
    { id: 1, name: 'Wayne', age: 44 },
    { id: 2, name: 'David', age: 24 },
];

const result = mapArrayToProps(users, ['name', 'age']);

function mapArrayToProps(arr, props) {
    return arr.flatMap(obj => mapObjectToProps(obj, props));
}

function mapObjectToProps(obj, props) {
    return props.map(prop => obj[prop])
}

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.